如何使用 StreamWriter.WriteAsync 并捕获异常? [英] How to use StreamWriter.WriteAsync and catch exceptions?

查看:34
本文介绍了如何使用 StreamWriter.WriteAsync 并捕获异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有简单的写文件功能.

I have simple function to write files.

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?

How can I convert my code to use StreamWriter.WriteAsync with try-catch?

推荐答案

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

这篇关于如何使用 StreamWriter.WriteAsync 并捕获异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆