How do I read an embedded resource (text file) using StreamReader
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();
strValuesToSearch.Add("Apple");
string stringToReplace;
stringToReplace = textBox1.Text;
StreamReader FileReader = new StreamReader(@"C:\MyFile.txt");
string FileContents;
FileContents = FileReader.ReadToEnd();
FileReader.Close();
foreach (string s in strValuesToSearch)
{
if (FileContents.Contains(s))
FileContents = FileContents.Replace(s, stringToReplace);
}
StreamWriter FileWriter = new StreamWriter(@"MyFile.txt");
FileWriter.Write(FileContents);
FileWriter.Close();
}
You can use the
Assembly.GetManifestResourceStream
Method:Add the following usings
Set property of relevant file:
Parameter
Build Action
with valueEmbedded Resource
Use the following code
resourceName
is the name of one of the resources embedded inassembly
. 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"
, thenresourceName
is"MyCompany.MyProduct.MyFile.txt"
. You can get a list of all resources in an assembly using theAssembly.GetManifestResourceNames
Method.A no brainer astute to get the
resourceName
from the file name only (by pass the namespace stuff):I was annoyed that you had to always include the namespace and the folder in the string. I wanted to simplify the access to the embedded resources. This is why I wrote this little class. Feel free to use and improve!
Usage:
Class:
I know it is an old thread, but this is what worked for me :
read the text like this :
The text that I added to the resources: 'SomeText.txt'
When you added the file to the resources, you should select its Access Modifiers as public than you can make something like following.
CLIST01 is the name of the embedded file.
Actually you can go to the resources.Designer.cs and see what is the name of the getter.
You can also use this simplified version of @dtb's answer: