How can I modify this method to call it asynchronously?
private void Write(string fileName, data)
{
File.WriteAllText(fileName, data);
}
Look into FileStream.WriteAsync
(Note you have to use the proper overload which takes a bool
indicating if it should run async:)
public async Task WriteAsync(string data)
{
var buffer = Encoding.UTF8.GetBytes(data);
using (var fs = new FileStream(@"File", FileMode.OpenOrCreate,
FileAccess.Write, FileShare.None, buffer.Length, true))
{
await fs.WriteAsync(buffer, 0, buffer.Length);
}
}
Edit
If you want to use your string data
and avoid the transformation to a byte[]
, you can use the more abstracted and less verbose StreamWriter.WriteAsync
overload which accepts a string:
public async Task WriteAsync(string data)
{
using (var sw = new StreamWriter(@"FileLocation"))
{
await sw.WriteAsync(data);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With