65.9K
CodeProject is changing. Read more.
Home

Read a Resource File from an assembly

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.71/5 (8 votes)

Feb 14, 2017

CPOL
viewsIcon

13881

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: 

        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):

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

Will return the entire text.

History

  • 2017-02-14 First version