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

时间:2013-09-22 11:02:47

标签: c# asynchronous try-catch .net-4.5 streamwriter

我有简单的函数来写文件。

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();
}

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

1 个答案:

答案 0 :(得分:2)

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();
    }
}