howto embed a textfile into an exe

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,

What I want is to add a text file to my project which will be
included/embedded in my exe file.
So not a link to a text file in a folder but a text file physical in the exe.

Is this possible..? How can I access the content of the file..?

Jan
 
Yes this is possible. Simply add the file to your solution, set the
properties of the file withon the project to "Embedd Resource" and load the
file at runtime.

You will have to use a fully qualified name for the file such as
"MyAssembly.MyFolder.MyFile.txt" and you can use the
Assembly.GetManifestResourceStream to fetch the file into a stream that you
can read.

For a similar example of how to embed a font into an application see the
GDI+ FAQ. This has all the principles, you can just change the details to
deal with the text file case.

--
Bob Powell [MVP]
Visual C#, System.Drawing

Ramuseco Limited .NET consulting
http://www.ramuseco.com

Find great Windows Forms articles in Windows Forms Tips and Tricks
http://www.bobpowell.net/tipstricks.htm

Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/faqmain.htm

All new articles provide code in C# and VB.NET.
Subscribe to the RSS feeds provided and never miss a new article.
 
Hi,

Add the file to the project, select it in the project explorer, click
properties, select "embedded resource"
then use this code to extract it:

static string ExtractResource( string resourceName)
{
//look for the resource name
foreach( string currentResource in
System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceNames()
)
if ( currentResource.LastIndexOf( resourceName) != -1 )
{
string fqnTempFile = System.IO.Path.GetTempFileName();
string path = System.IO.Path.GetDirectoryName( fqnTempFile);
string rootName= System.IO.Path.GetFileNameWithoutExtension(
fqnTempFile);
string destFile = path + @"\" + rootName + "." +
System.IO.Path.GetExtension( currentResource);

System.IO.Stream fs =
System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(
currentResource);

byte[] buff = new byte[ fs.Length ];
fs.Read( buff, 0, (int)fs.Length);
fs.Close();

System.IO.FileStream destStream = new System.IO.FileStream ( destFile,
FileMode.Create);
destStream.Write( buff, 0, buff.Length);
destStream.Close();

return destFile;
}

throw new Exception("Resource not found : " + resourceName);

}


cheers,
 
Back
Top