Read a Document in a .Net Core Application Baked into the Project File

March 15, 2019

This isn’t a difficult thing to achieve, but it is one that frequently has me reaching for Google to get the exact syntax. By creating this post (I create all my posts on OneNote first), it’s now offline for me.

There’s more than one way to do this; I’ve covered two. All the examples here are using a CSV file from an Assets folder:

Embedded Resource

These are embedded into the compiled assembly; which means in order to change them, you would need to recompile your code. This works well for images, but less well for data files.

First, you need to add your resource to your project, and set the properties to be an embedded resource:

Because it’s embedded, copying makes no sense. To read the file:

public string GetResourceTextFile(string filename)
    using Stream stream = this.GetType().Assembly.
    using StreamReader sr = new StreamReader(stream);                           
    return sr.ReadToEnd();


This allows you to include a file within your project; however, content files are not compiled. Combined with the “Copy To Output Directory” they place files in the binary directory of your project. The advantage here is that you can change this file after compilation:

Because this just copies the file to the executing directory, it’s easier to read the file:

public string GetContentTextFile(string filename)
    return File.ReadAllText($"Assets/{filename}");


Profile picture

A blog about one man's journey through code… and some pictures of the Peak District

© Paul Michaels 2022