Creating a file asynchronously
With .NetCore 2.0 you can just use File.WriteAllTextAsync
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);
}
}