tags:

views:

60

answers:

2

How do I read using Streamreader an embedded resource (txt file)? (and return it as a string?) My current script uses a windows form and texbox 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();
}
A: 

Take a look at this page: http://support.microsoft.com/kb/319292

Basically, you use System.Reflection to get a reference to the current Assembly. Then, you use GetManifestResourceStream().

Example, from the page I posted:

Note: need to add using System.Reflection; for this to work

   Assembly _assembly;
   StreamReader _textStreamReader;

   try
   {
      _assembly = Assembly.GetExecutingAssembly();
      _textStreamReader = new StreamReader(_assembly.GetManifestResourceStream("MyNamespace.MyTextFile.txt"));
   }
   catch
   {
      MessageBox.Show("Error accessing resources!");
   }
SimpleCoder
+1  A: 

You can use the Assembly.GetManifestResourceStream Method:

using (Stream stream = Assembly.GetExecutingAssembly()
                               .GetManifestResourceStream("file1.txt"))
using (StreamReader reader = new StreamReader(stream))
{
    string result = reader.ReadToEnd();
}
dtb
Great, thanks man. I had a second question regarding the save path, how would I specify it so it would save it to the desktop on any computer which would perhaps have different directory structure?
Me.Close
@Me.Close: Have a look at [`Environment.SpecialFolder`](http://msdn.microsoft.com/en-us/library/system.environment.specialfolder.aspx) to get the desktop folder. You need to bear in mind that the resource will be namespaced based on its path within the project, so its name may not be just `file1.txt`.
adrianbanks