The .NET Framework has some useful static utility functions that make reading files simple, but where are the async versions? In this post I will show you a simple way to create an Asynchronous ReadAllTextAsync
function.
File.ReadAllText("example.txt")
is really useful, but what if you want to do it using the async/await pattern. I couldn’t find a ReadAllTextAsync
method so here is a simple utility class that you can use instead.
Code Example
public static class FileUtil
{
public static async Task<string> ReadAllTextAsync(string filePath)
{
var stringBuilder = new StringBuilder();
using (var fileStream = File.OpenRead(filePath))
using (var streamReader = new StreamReader(fileStream))
{
string line = await streamReader.ReadLineAsync();
while(line != null)
{
stringBuilder.AppendLine(line);
line = await streamReader.ReadLineAsync();
}
return stringBuilder.ToString();
}
}
}
Usage Example
string text = FileUtil.ReadAllTextAsync("example.txt");