Read or Write Resources from/into a DLL in .NET 2.0

I created a Windows Live Writer plug-in for inserting Smileys a while ago. It depends on a TXT file which was initially present under Application Folder + "\Plugin" folder. Recently, due to design changes in the beta version of WLW, the plug-in started crashing due to the missing Text file! So the question here is, how do we get rid of these problems?

One way which I find quite easy is... embed the resource file (in my case the .TXT file) in your DLL if you like. This blog post is just about that...

1. For Demo purpose, you can create a new Project (ReadWriteResourceFromDLLorEXE)
2. Add a new TextFile to the project

image

3. Right click MyTextFile.txt and select Properties
4. Change the Build Action to Embedded Resource
5. Now drag and drop a button on Form1.cs.
6. Create a Textbox with multiline property set to true.

image

7. Paste the following code in button click event...

         private void button1_Click(object sender, EventArgs e)
        {
            //Declare a StreamReader and a StreamWriter
            StreamReader strmrStreamReader;
            StreamWriter strmrStreamWriter = new StreamWriter(Application.StartupPath + "\\NewFile.txt");
            //Extract the Resource using this line. Notice the namespace... ReadWriteResourceFromDLLorEXE!
            strmrStreamReader = new 
                StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream
                ("ReadWriteResourceFromDLLorEXE.MyTextFile.txt"));
            //Here we are creating a new file in the Application Startup path, and for fun
            //we are also changing the name to NewFile.txt
            if (strmrStreamReader.Peek() != -1) 
                strmrStreamWriter.Write(strmrStreamReader.ReadToEnd());
            //We are done with the files now, lets close it up
            strmrStreamReader.Close();
            strmrStreamWriter.Close();
            //Now, show the file in the Multiline Textbox
            strmrStreamReader = new StreamReader(Application.StartupPath + "\\NewFile.txt");
            textBox1.Text = strmrStreamReader.ReadToEnd().ToString();
            strmrStreamReader.Close();
        }

8. Start the program and you should be all set. Notice that after you run the program, you will see that the new file is created under Debug folder.

image

Until next time Wave
Rahul

Share this post :