Skip to content

Instantly share code, notes, and snippets.

@yetanotherchris
Last active December 12, 2015 10:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yetanotherchris/4757683 to your computer and use it in GitHub Desktop.
Save yetanotherchris/4757683 to your computer and use it in GitHub Desktop.
Embedded resources example
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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment