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.GetManifestResourceStreamMethod:Add the following usings
Set property of relevant file:
Parameter
Build Actionwith valueEmbedded ResourceUse the following code
resourceNameis 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", thenresourceNameis"MyCompany.MyProduct.MyFile.txt".You can get a list of all resources in an assembly using the
Assembly.GetManifestResourceNamesMethod.A no brainer astute to get the
resourceNamefrom the file name only (by pass the namespace stuff):A complete example:
or as an async extension method: