Top

Tags


Roadkill .NET Wiki

Google ads

Recommended reading


Search

Sunday
Nov152009

Embedded resources example

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;
    }
}

Reader Comments

There are no comments for this journal entry. To create a new comment, use the form below.

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>
« Value types, reference types, boxing and unboxing in C# | Main | Abstract methods vs Virtual methods »