Scenario
There are several cases in which reading text from a file is more is more convenient than writing a string in the middle of my code. I've done this occasionally for SQL statements, text templates, and unit testing sample XML or JSON. For my money, it keeps the code looking cleaner and easier to read, as well as having the added benefit of syntax highlighting for whatever language the string is written for.
Solution
In these cases, I set the binary file as an 'Embedded Resource' in Visual studio and add an Assembly Extension.
In this example, we'll read a file named MyFile.json
Setting up the file
To keep my solution clean, I like to keep files that I intend to keep in source control and read in a 'Resource' folder in my solution, which prevent random files from appearing all over the place. In our project, we'll create a new folder 'Resource' and it it, a new file called 'MyFile.json'. Next I change File Properties -> Advanced -> Build Action to 'Embedded Resource' for MyFile.json.
The Assembly Extension
Next, I get ahold of the file stream and return it as text using the following class and a little reflection:
public static class AssemblyExtension
{
public static string ReadTextResource(this Assembly assembly, string resourceName)
{
using (var stream = assembly.GetManifestResourceStream(resourceName))
{
if (stream == null) throw new ApplicationException("Resource yielded null stream");
if (stream.Length == 0) throw new ApplicationException("Resource is empty");
using (var reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}
}
Reading the Resource
Finally, I can read the resource. Reflection can be used to make the call a little cleaner, but to simply pull the file, the call would look like this:
var assembly = Assembly.GetExecutingAssembly();
var resourceString = assembly.ReadTextResource("MyAssembly.Resource.MyFile.json");
Software Development Nerd