问题
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?
回答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();
}
}
来源:https://stackoverflow.com/questions/18943154/how-to-use-streamwriter-writeasync-and-catch-exceptions