如何使用 StreamWriter.WriteAsync 并捕获异常

本文关键字:捕获异常 WriteAsync StreamWriter 何使用 | 更新日期: 2023-09-27 18:32:29

>我有一个简单的功能来写文件。

public static void WriteFile(string filename, string text)
{
    StreamWriter file = new StreamWriter(filename);
    try
    {
        file.Write(text);
    }
    catch (System.UnauthorizedAccessException)
    {
        MessageBox.Show("You have no write permission in that folder.");
    }
    catch (System.Exception e)
    {
        MessageBox.Show(e.Message);
    }
    file.Close();
}

如何将我的代码转换为将StreamWriter.WriteAsync与 try-catch 一起使用?

如何使用 StreamWriter.WriteAsync 并捕获异常

async public static void WriteFile(string filename, string text)
{
    StreamWriter file = null;
    try
    {
        file = new StreamWriter(filename);
        await file.WriteAsync(text);
    }
    catch (System.UnauthorizedAccessException)
    {
        MessageBox.Show("You have no write permission in that folder.");
    }
    catch (System.Exception e)
    {
        MessageBox.Show(e.Message);
    }
    finally
    {
        if (file != null) file.Close();
    }
}