Wednesday, 20 October 2010

Read an Embedded Resource Text File in C#

Here's a little snippet I use quite a lot in my test projects to read out an embedded resource text file as a string. The resourceName parameter is the full namespace of the resource, e.g. myproject.files.MyEmbeddedTextFile.txt

internal string GetFromResources(string resourceName)
{
    Assembly assem = this.GetType().Assembly;
    using (Stream stream = assem.GetManifestResourceStream(resourceName))
    {
        using (var reader = new StreamReader(stream))
        {
            return reader.ReadToEnd();
        }
    }
}

P.S. You may want to add some error handling to the above ;)

3 comments:

  1. You can also get tooling support in the IDE if you add a RESX file and then drag files from the solution into the files section of the RESX designer.

    This generates static methods for accessing it in much the same way as adding a Settings file. Additional benefit is that you can then add localised RESX files (e.g. ResourceFileName.es.resx) that compile as satellite assemblies and then that file gets read for when that culture is set.

    Advantage is it's then all typed and you don't have any magic strings in your code.

    ReplyDelete
  2. @Neil: I have been trying this approach and, for the life of me, cannot seem to figure out the name of the resource. I have tried sending in every (boolean) combination I can think of for the solutionName, NamespaceName, dllName as prefixes to the fileName.csv -- and I always get a null Stream. Any suggestions?

    @Ian: neat! It is not obvious (to me) how to access the file as a Stream instead of a String. I am currently loading .csv files so perhaps the IDE is auto-detecting. The generated code is clearly returning String.

    ReplyDelete
  3. Wow, really useful Ian. Every day is a school day :)

    ReplyDelete