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:

content files 1

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:

content files 2

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



public string GetResourceTextFile(string filename)
{
    using Stream stream = this.GetType().Assembly.
                       GetManifestResourceStream($"SalesOrder.Generate.{filename}");
    using StreamReader sr = new StreamReader(stream);                           
            
    return sr.ReadToEnd();
}

Content

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:

content files 3

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}");
}

References

https://stackoverflow.com/questions/145752/what-are-the-various-build-action-settings-in-visual-studio-project-properties



Profile picture

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

© Paul Michaels 2024