In the previous article, the included utility used a text file as a source, and wrote a code snippet that created and populated a string variable for you to use in your own code. This article takes a different approach by embedding the text file in your assembly and extracting it when needed.
The main advantage to this approach is maintainability. Since the text is not cut up by concatenation or
StringBuilder.Append statements, it's easy to read and edit.
Using the code
Setting up the text file can be accomplished in 3 easy steps:
- Add a text file to your solution.
- Right-click on the file in the Solution Explorer and select "properties" to display the Properties window for the file.
- Change the "Build Action" to "Embedded Resource".
Once this is done, your file will be embedded in the assembly the next time you compile. Its contents can be read back using the following
GetFromResources method and used to populate your string variable to be used in your application.
The code consists of a small method to extract the resource file as a string. Using reflection, a reference to the current assembly is created. Then, with the manifest reader method
GetManifestResourceStream, the text file is read and returned as a string. That's it!
internal string GetFromResources(string resourceName)
Assembly assem = this.GetType().Assembly;
using( Stream stream = assem.GetManifestResourceStream(resourceName) )
using( StreamReader reader = new StreamReader(stream) )
throw new Exception("Error retrieving from Resources. Tried '"
Using the method to populate a string variable is accomplished in one line of code:
string quote =
Key Points to Remember:
resourceName is case sensitive.
resourceName must be the fully qualified name of the file: Default Namespace + folder name(s) + filename (with extension if applicable).
- Your code file will need to have
using statements for
System.IO. If you only change the text of an embedded resource file, you will need to rebuild your project because Visual Studio does not recognize the change as a code change worthy of recompiling.
I want to stress the last key point again. Several times I have changed only the embedded resource file and run my application only to see the old text returned. This can be pretty frustrating, especially if the expected change is buried deep in your application. If you remember that you need to rebuild your application after an embedded resource change, you'll be a much happier programmer.