Last active
December 12, 2015 10:18
-
-
Save yetanotherchris/4757683 to your computer and use it in GitHub Desktop.
Embedded resources example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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