• Home
  • Tutorials
  • Development Tools
  • Contact Us

Developing Software

Mastering Software Craftsmanship

How to Read All Text from a File with C# using Async/Await (File.ReadAllTextAsync)

11th March 2016 by @developingsoft

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");
Share this on:

Filed Under: Tutorials Tagged With: C#

Search

Advertisement

Newsletter

Subscribe now to receive practical tips on how to become a better software developer.

Free - No Spam - 100% Email Privacy

Featured Posts

Abstract Factory Pattern: C# Example Using the Unity Game Engine

23 Software Design Patterns That Will Make You a More Effective Programmer

How to Deploy an ASP.NET Core Website to Ubuntu with Git

How to Run an ASP.NET Core Website in Production on Ubuntu Linux

How to Install the Edimax Wireless nano USB Adapter on Windows IoT Core for Raspberry Pi

How to Convert a Post Title into a Friendly URL (Slug) in C#

How to Convert Markdown to HTML in ASP.NET Core

How to Send an E-Mail with ASP.NET Core and Mailgun

How to Generate a Sitemap in ASP.NET MVC and ASP.NET Core

How to Create an MD5 Hash of a String in C# and Displaying a Gravatar Image

© 2014–2025 Developing SoftwareTerms • Privacy