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

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

问题描述

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

 公共静态无效WriteFile的(字符串的文件名,字符串文本)
{
    StreamWriter的文件=新的StreamWriter(文件名);
    尝试
    {
        file.Write(文本);
    }
    赶上(System.UnauthorizedAccessException的)
    {
        的MessageBox.show(您有一个文件夹的写权限。);
    }
    赶上(System.Exception的E)
    {
        MessageBox.Show(e.Message);
    }    file.Close();
}

如何转换我的code使用 StreamWriter.WriteAsync 用的try-catch?


解决方案

 异步公共静态无效WriteFile的(字符串的文件名,字符串文本)
{
    StreamWriter的文件= NULL;
    尝试
    {
        文件=新的StreamWriter(文件名);
        等待file.WriteAsync(文本);
    }
    赶上(System.UnauthorizedAccessException的)
    {
        的MessageBox.show(您有一个文件夹的写权限。);
    }
    赶上(System.Exception的E)
    {
        MessageBox.Show(e.Message);
    }
    最后
    {
        如果(文件!= NULL)file.Close();
    }
}

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

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天全站免登陆