/ lemonsnippet

Async File Read/Write in .Net Standard 2

I was creating a Winforms app (.Net FX 4.72)(just for q&d testing you understand) and I needed to reference one of my shared dlls that was .Net Core 2. Unfortunately, you cant do this. It has to be .Net Standard.

When I changed the shared dll project to .Net Standard 2 I had a compile error for File.ReadAllTextAsync() and File.WriteAllTextAsync(). These don't exist in the standard.

It was hard to find any info on this - probably because the solution is simple/obvious. The methods exist in .Net Core 2.0 but I'm not sure they will be added to the standard. Given the simplicity of the replacement, maybe not.

Instead of this:

var text = await File.ReadAllTextAsync(filename);

do this:

string text;
using (var sourceReader = File.OpenText(fileName))
  text = await sourceReader.ReadToEndAsync();

And instead of :

await File.WriteAllTextAsync(filename, text);

do this:

using (var writer = File.CreateText(fileName))
    await writer.WriteAsync(text);