我有简单的函数来写文件。
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
?
答案 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();
}
}