Open Solution Explorer add files you want to embed. Right click on the files then click on Properties . In Properties window and change Build Action to Embedded Resource . After that you should write the embedded resources to file in order to be able to run it.
Right-click the project file, select Properties.
In the window that opens, go to the Resources tab, and if it has just a blue link in the middle of the tab-page, click it, to create a new resource.
Then from the toolbar above the tab-page, select to add a new text file, give it a name, it will be added to your project and opened up.
If you get this far, then in your code you can type in Resources.TheNameYouGaveTheTextFileHere and you can access its contents. Note that the first time you use the Resources class in a class, you need to add a using directive (hit Ctrl+. after typing Resources to get the menu to get VS to do it for you).
If something was unclear about the above description, please leave a comment and I'll edit it until it is complete or makes sense :)
In Visual Studio 2003, Visual Studio 2005 and possibly earlier versions (this works in 2008 as well) you can include the text file in your project, then in the 'Properties' panel, set the action to 'Embedded Resource'. Then you can access the file as a stream using Assembly.GetManifestResourceStream(string)
.
Other answers here are more convenient. I include this for completeness.
Note that this approach will work for embedding other types of files such as images, icons, sounds, etc...
After embeding a text file, use that file any where in code like this...
global::packageName.Properties.Resources.ThatFileName
Here's what worked for me. (I needed to read contents of a file embedded into an executable .NET image file.)
Before doing anything, include your file into your solution in Visual Studio. (In my case VS 2017 Community.) I switched to the Solution Explorer
, then right-clicked Properties
folder, chose Add Existing Item
and picked the file. (Say, FileName.txt
.) Then while still in the Solution Explorer
, right-click on the included file, select Properties
, and pick Build Action
as Embedded Resource
.
Then use this code to read its bytes:
string strResourceName = "FileName.txt";
Assembly asm = Assembly.GetExecutingAssembly();
using( Stream rsrcStream = asm.GetManifestResourceStream(asm.GetName().Name + ".Properties." + strResourceName))
{
using (StreamReader sRdr = new StreamReader(rsrcStream))
{
//For instance, gets it as text
string strTxt = sRdr.ReadToEnd();
}
}
Note, that in this case you do not need to add that file as a resource as was proposed in the accepted answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With