Read Embedded Resource Text File C#

c#
Author

Martyn Jones

Published

November 12, 2022

In a C# console app that I was developing, I had a set of text files that I needed to use the contents of at runtime.

I did not want to take the contents of the files and make them C# source code, as that made it more complicated for our Data Scientists, who populate the text files, to update their contents over time.

Initially, I added the text files to the project and set them to copy to the output on build. This was a bit messy with how to read the files back in for unit tests vs normal running.

I did try out the TxtToListGenerator source generator, but, one of the files is over 300,000 lines and this did cause the build to hang, so I went for a less complex solution.

I decided to set the text files as embedded resources and then read them from the assembly at runtime.

With the files added to the project as embedded resources, the code to read them at runtime is:

using System;
using System.IO;
using System.Linq;
using System.Reflection;

/// <summary>
/// </summary>
/// <param name="resourceFileName">The name of an embedded resource text file to read in.</param>
private string[] ReadResourceTextLines(string resourceFileName)
{
    var assembly = Assembly.GetExecutingAssembly();

    var resourcePath = assembly
        .GetManifestResourceNames()
        .Single(str => str.EndsWith(resourceFileName));

    using var stream = assembly.GetManifestResourceStream(resourcePath);
    using var reader = new StreamReader(stream);

    return reader
        .ReadToEnd()
        .Split(Environment.NewLine);
}