Chris's coding blog

Embedded resources example

November 15, 2009

This is a small example showing the discover and reading of all embedded resources in your assembly.

On a slight but vaguely related tangent - one of the better guides on localization can be found here.

static void Main(string[] args)
{
ResourceExample example = new ResourceExample();
example.Show();
Console.WriteLine("------------");
// Case sensitive
string output = example.GetStringFromResource("Mynamespace.Folder1.Folder2.Example.txt");
Console.WriteLine(output);
Console.ReadLine();
}
public class ResourceExample
{
/// <summary>
/// Prints the full namespace path of each resource in the assembly.
/// </summary>
public void Show()
{
foreach (string name in this.GetType().Assembly.GetManifestResourceNames())
{
Console.WriteLine(name);
}
}
/// <summary>
/// Reads an embedded resource as a text file, from the given path.
/// </summary>
/// <param name="path">The full namespace path to the embedded resource.</param>
/// <returns>The string contents of the file.</returns>
public string GetStringFromResource(string path)
{
if (string.IsNullOrEmpty(path))
throw new ArgumentNullException("path", "The path is null or empty");
Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(path);
if (stream == null)
throw new InvalidOperationException(string.Format("Unable to find '{0}' as an embedded resource", path));
string result = "";
using (StreamReader reader = new StreamReader(stream))
{
result = reader.ReadToEnd();
}
return result;
}
}
view raw gistfile1.cs hosted with ❤ by GitHub

csharp

I'm Chris Small, a software engineer working in London. This is my tech blog. Find out more about me via GithubStackoverflowResume