views:

1792

answers:

3

I would like to embed a text file in an assembly so that I can load the text without having to read it from disk, and so that everything I need is contained within the exe. (So that it's more portable)

Is there a way to do this? I assume something with the resource files?

And if you can, how do you do it and how do you programaticaly load the text into a string?

A: 

Yes, you are correct - create a resource file. WHen you do that you don't need to "load" the string, it will be referenced as Resource.WhateverStringYouDefined.

Otávio Décio
+10  A: 

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 :)

Lasse V. Karlsen
What would the 'using' directive code look like, I'm struggling to make this work. I've added the solutions.txt as a resource, but it can't find Resources.solutions - I feel I'm missing the using directive.
Spedge
Ah-hah, all I needed to do was add a My. to the front (i.e. My.Resources.solutions) Simples!
Spedge
+5  A: 

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...

Drew Noakes
Note: Use the namespace + filename as parameter for GetManifestResourceStream(), e.g. "MyNamespace.MyTextfile.txt". You can also call GetManifestResourceNames() to get a list of all names.
Stiefel