Dork Dork - 5 months ago 36
C# Question

Reading a file from resources

I have embed

sample.txt
(it contains just one line "aaaa" ) file into project's resources like in this answer.
When I'm trying to read it like this:

string s = File.ReadAllText(global::ConsoleApplication.Properties.Resources.sample);


I'm getting System.IO.FileNotFoundException' exception.
Additional information: Could not find file 'd:\Work\Projects\MyTests\ConsoleApplication\ConsoleApplication\bin\Debug\aaaa'.

So seemingly it's trying to take file name from my resource file instead of reading this file. Why is this happening? And how can I make it read sample.txt

Trying solution of @Ryios and getting Argument null exception

using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("ConsoleApplication.Resources.sample.txt"))
{
TextReader tr = new StreamReader(stream);
string fileContents = tr.ReadToEnd();
}


The file is located in d:\Work\Projects\MyTests\ConsoleApplication\ConsoleApplication\Resources\sample.txt

p.s. Solved. I had to set Build Action - embed resource in sample.txt properties

Answer Source

You can't read Resource Files with File.ReadAllText.

Instead you need to open a Resource Stream with Assembly.GetManifestResourceStream.

You don't pass it a path either, you pass it a namespace. The namespace of the file will be the Assemblies Default Namespace + The folder heieracy in the project the file is in + the name of the file.

Imagine this structure

  • Project (xyz.project)
    • Folder1
      • Folder2
        • SomeFile.Txt

So the namespace for the file will be:

xyz.project.Folder1.Folder2.SomeFile.Txt

Then you would read it like so

        using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("xyz.project.Folder1.Folder2.SomeFile.Txt"))
        {
            TextReader tr = new StreamReader(stream);
            string fileContents = tr.ReadToEnd();
        }