【问题标题】:How to use StreamWriter.WriteAsync and catch exceptions?如何使用 StreamWriter.WriteAsync 并捕获异常?
【发布时间】:2013-09-22 19:29:31
【问题描述】:

我有简单的写文件功能。

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?

【问题讨论】:

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


    【解决方案1】:
    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();
        }
    }
    

    【讨论】:

    • 我试过这个。 VS 说:The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.
    • Aaah 方法名称前有async。我没看到这个。现在它可以编译了,但是当我尝试在 windows 目录中写入时 - 没有错误的 MessageBox。
    • 我有“在 mscorlib.dll 中发生'System.Reflection.TargetInvocationException' 类型的未处理异常”而不是带有“您在该文件夹中没有写入权限”的 MessageBox。
    • @Kamil 请出示您的真实代码。当我运行上面的代码时,我看到了消息框。
    • 这是真实的代码。我只是将消息框中的文本翻译成英文。我将添加调用该方法的代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-09
    • 1970-01-01
    • 2018-01-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多