Prabhu
Prabhu

Reputation: 13355

Creating a file asynchronously

How can I modify this method to call it asynchronously?

private void Write(string fileName, data)
{
    File.WriteAllText(fileName, data);           
}

Upvotes: 17

Views: 14864

Answers (2)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149628

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);
    }
}

Upvotes: 28

AmitE
AmitE

Reputation: 894

With .NetCore 2.0 you can just use File.WriteAllTextAsync

Upvotes: 14

Related Questions