Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.