Getting hold of embedded resources is a bit of a fiddle, here's some simple extensions to simplify this

It works by convention, as is the fashion. Simply it checks the assembly of a given type for any resource which ends with ".[filename and extension]" and returns the first one

This returns a stream

public static Stream FindResourceStream(
        this Type type, string name)
{
    return (from r in type.Assembly.GetManifestResourceNames()
            where r.EndsWith("." + name)
            select type.Assembly
                       .GetManifestResourceStream(r))
           .FirstOrDefault();
}

This returns a whatever, transformed from a stream

public static T FindResource<T>(
        this Type type, string name,
        Func<Stream,T> transformer) {

    return transformer(
        FindResourceStream(type, name));
}

And this a string

public static string FindResourceString(
        this Type type, string name) 
{
    return FindResource(type, name,
        s =>
            {
                using (var reader = new StreamReader(s))
                    return reader.ReadToEnd();
            });
}

And finally an image

public static Image FindResourceImage(
        this Type type, string name)
{
    return FindResource(type, name, Image.FromStream);
}

With all but the stream one, the calling function is responsible for disposal so bear this in mind or you may end up in Out of Memory territory

Usage

I have put a file in my project under a directory called Resources and marked it as Embedded Resource, you can get hold of it from any class in the same project

Now you can just call the extension on the current type or another type in the same assembly as the resource

var webPage = GetType().FindResourceString("WebPage.htm");
var webPage = typeof(MyClass).FindResourceString("WebPage.htm");

and an image, like so

using (var image = GetType().FindResourceImage("Image.png")) {
    ...
}

These extensions are part of antix-testing, available on NuGet

Post a Note

(required)

(required never shown)

On Twitter Follow MrAntix on Twitter

a minute ago
TJTechnology
Active Authentication For Secure Access To Windows Azure Enabled For Enterprises : http://t.co/g6Rs0to6Q2

a minute ago
NigelFrank
Microsoft Dynamics GP and NAV are now available on Windows Azure. Find out more at http://t.co/lWhxM0eyDs via @pcworld #msdyngp #msdynnav

7 minutes ago
_contentmaster
Huge collection of free e-books from #Microsoft - including many contributions from Content Master authors: http://t.co/C9M9tr4BJ3.

7 minutes ago
dtplk
RT @maryjofoley: Free Microsoft eBooks on IT products/topics (O365, SharePoint, SQL Server, Azure, VS, Win Server, etc.) http://t.co/k1RiVX…

9 minutes ago
MobileByDesign
RT @maryjofoley: Free Microsoft eBooks on IT products/topics (O365, SharePoint, SQL Server, Azure, VS, Win Server, etc.) http://t.co/k1RiVX…