Me.Close Me.Close - 1 year ago 186
C# Question

How to read embedded resource text file

How do I read an embedded resource (text file) using

and return it as a string? My current script uses a Windows form and textbox that allows the user to find and replace text in a text file that is not embedded.

private void button1_Click(object sender, EventArgs e)
StringCollection strValuesToSearch = new StringCollection();
string stringToReplace;
stringToReplace = textBox1.Text;

StreamReader FileReader = new StreamReader(@"C:\MyFile.txt");
string FileContents;
FileContents = FileReader.ReadToEnd();
foreach (string s in strValuesToSearch)
if (FileContents.Contains(s))
FileContents = FileContents.Replace(s, stringToReplace);
StreamWriter FileWriter = new StreamWriter(@"MyFile.txt");

dtb dtb
Answer Source

You can use the Assembly.GetManifestResourceStream Method:

  1. Add the following using

    using System.Reflection;
  2. Set property of relevant file:
    Parameter Build Action with value Embedded Resource

  3. Use the following code

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

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

resourceName is the name of one of the resources embedded in assembly. For example, if you embed a text file named "MyFile.txt" that is placed in the root of a project with default namespace "MyCompany.MyProduct", then resourceName is "MyCompany.MyProduct.MyFile.txt". You can get a list of all resources in an assembly using the Assembly.GetManifestResourceNames Method.