Reading an embedded text file

Botle Khauhelo picture Botle Khauhelo · Aug 7, 2013 · Viewed 17k times · Source

I have created a full project which works perfectly. My problem concerns the setup project. When I use it on another computer, the text file cannot be found even if they are inside the resource folder during the deployment!

How can I ensure that my program will find those text files after installing the software on another computer!

I have been looking for this solution but in vain. Please help me sort this out. If I can get a full code that does that i will be very happy!

Answer

Simon P Stevens picture Simon P Stevens · Aug 7, 2013

FIrst set the build action of the text file to "EmbeddedResource".

Then to read the file in your code:

var assembly = Assembly.GetExecutingAssembly();
var resourceName = "AssemblyName.MyFile.txt";

using (Stream stream = assembly.GetManifestResourceStream(resourceName))
{
    using (StreamReader reader = new StreamReader(stream))
    {
        string result = reader.ReadToEnd();
    }
}

If you can't figure out the name of the embedded resource do this to find the names and it should be obvious which your file is:

assembly.GetManifestResourceNames();

This is assuming you want the text file to be embedded in the assembly. If not, then you might just want to change your setup project to include the text file during the installation.