Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a file asynchronously

How can I modify this method to call it asynchronously?

private void Write(string fileName, data)
{
    File.WriteAllText(fileName, data);           
}
like image 327
Prabhu Avatar asked Aug 27 '14 07:08

Prabhu


1 Answers

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);
    }
}
like image 101
Yuval Itzchakov Avatar answered Oct 03 '22 18:10

Yuval Itzchakov