Click here to Skip to main content
15,868,016 members
Articles / Programming Languages / C#
Tip/Trick

Read a Resource File from an assembly

Rate me:
Please Sign up or sign in to vote.
4.71/5 (8 votes)
13 Feb 2017CPOL 12.5K   5   4
I embed a ToDo.txt and a RevisionHistory.txt file in every assembly - it helps me keep track of what has changed - and it normally gets read out and displayed in the "Help...About" dialog. But what if you want to read an embedded file from a different Assembly?

Introduction

It's really easy to do: 

C#
string GetResourceFile(string assemblyPath, string nameSpace, string fileName)
    {
    Assembly assembly = Assembly.LoadFrom(assemblyPath);
    string resourceName = nameSpace + "." + fileName;
    string resource = null;
    using (Stream stream = assembly.GetManifestResourceStream(resourceName))
        {
        using (StreamReader reader = new StreamReader(stream))
            {
            resource = reader.ReadToEnd();
            }
        }
    return resource;
    }

Using the Code

Simple! Assuming MyAssembly has a folder "Resources", containing a folder "TextFiles", containing an embedded resource text file "RevisionHistory.txt" (which it does):

C#
GetResourceFile(@"D:\Testing\MyAssembly.dll", "MyAssembly.Resources.TextFiles", "RevisionHistory.txt");

Will return the entire text.

History

  • 2017-02-14 First version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
CEO
Wales Wales
Born at an early age, he grew older. At the same time, his hair grew longer, and was tied up behind his head.
Has problems spelling the word "the".
Invented the portable cat-flap.
Currently, has not died yet. Or has he?

Comments and Discussions

 
GeneralMy vote of 5 Pin
Member 1236439020-Feb-17 0:47
Member 1236439020-Feb-17 0:47 
QuestionCould do with a little bit of bullet proofing Pin
Pete O'Hanlon13-Feb-17 23:29
subeditorPete O'Hanlon13-Feb-17 23:29 
AnswerRe: Could do with a little bit of bullet proofing Pin
OriginalGriff14-Feb-17 4:35
mveOriginalGriff14-Feb-17 4:35 
GeneralRe: Could do with a little bit of bullet proofing Pin
Pete O'Hanlon14-Feb-17 4:38
subeditorPete O'Hanlon14-Feb-17 4:38 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.