C# Programming > Miscellaneous

C# Embedded Resource

 

What's an Embedded Resource?

An embedded resource in a C# application is a file that is included as part of the application. The file is not compiled but is accessable from the code at run-time. Embedded resources can be any file type.

To add an embedded resource simply include an item as part of the C# project and set the Build Action to Embedded Resource.

Reading the Resource

Reading an embedded resource is similar to reading any type of file, i.e. we read it via a Stream. The tricky part is that the stream will come from an Assembly instance and you must make sure to use the right one. This makes sense since the file is embedded to a specific application.

Below is the code for reading an embedded resource as text (the download at the bottom includes the code for reading as a byte array):

public static string GetEmbeddedResource(string resourceName, Assembly assembly)
{
    resourceName = FormatResourceName(assembly, resourceName);
    using (Stream resourceStream = assembly.GetManifestResourceStream(resourceName))
    {
        if (resourceStream == null)
            return null;

        using (StreamReader reader = new StreamReader(resourceStream))
        {
            return reader.ReadToEnd();
        }
    }
}

Resource Name

One wrinkle is the name of the resource. Here is the format:

[assembly name].[resource name]

And here is a function:

private static string FormatResourceName(Assembly assembly, string resourceName)
{
    return assembly.GetName().Name + "." + resourceName.Replace(" ", "_")
                                                       .Replace("\\", ".")
                                                       .Replace("/", ".");
}

Notice that spaces are replaced with underscores and path separators are replaced with periods. This is would make a resource's name with path "Folder/file one.txt" be "Folder.file_one.txt".

Resource Helper

Download the source code at the bottom of the page for a helper class so you can do something like this:

string data = ResourceHelper.GetEmbeddedResource("Folder/file.txt");
Now you can easily read embedded resources from your C# applications.

Back to C# Article List