Manifest Resources vs. Stand-Alone Files

Problem
You want to know when and how to embed resources in your project.

Solution
You should favor using embedded resources for read-only data that will never change during your application’s lifetime. Use separate files to store data that the application can change or that you may want to deploy independently of the main application.

Pros & Cons
Resources that are embedded in the main assembly’s manifest can be located and loaded faster. They are also protected from accidental deletion. This technique is not best used when you have resources that are locale-dependent and should be localized for each language you support.

How-To
You can embed any data file in the assembly’s manifest by following these steps:
1. Add the file to the project.
2. Right-click the file and choose Properties.
3. Set the Build Action to Embedded Resource.

Example
The following code demonstrates how to programmatically access a text file named TestData.txt from inside an assembly whose default (root) namespace is TestAutomation.

string dataFile = "TestAutomation.TestData.txt";
// Get a reference to the assembly.
Assembly assembly = Assembly.GetExecutingAssembly();
Stream stream = assembly.GetManifestResourceStream(dataFile);
// Read the contents of the embedded file and close it.
StreamReader reader = new StreamReader(stream);
string text = reader.ReadToEnd();
reader.Close();

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s