Store files in C# EXE file

爷,独闯天下 提交于 2019-12-01 00:39:24

Add the files you want to your solution and then set their Build Action property to Embedded Resource. This will embed the file into your exe. (msdn)

Then you just need to write the code to write the file out to disk when the exe is executed.

Something like:

File.Copy("resource.bmp", @"C:\MyFile.bin");

Replace resource.bmp with your file name.

Addendum:

If you keep the file in a sub-folder in your solution you need to make the sub-folder part of the path to resource.bmp. Eg:

File.Copy(@"NewFolder1\resource.bmp", @"C:\MyFile.bin");

Also, you may need to set the Copy To Output Directory property to Copy Always or Copy If Newer.

I assume you added the files through the Project Properties window. That does not allow you to add an arbitrary file but it does support TextFiles, Bitmaps and so on.

For an embedded TextFile, use

  File.WriteAllText(@"C:\MyFile.bin", Properties.Resources.TextFile1);

For an Image, use

  Properties.Resources.Image1.Save(@"C:\MyFile.bin");

You can embed binary files in a .resx file. Put them in the Files section (it looks like you used the Images section instead). It should be accessible as an array of bytes if your .resx file generates a .Designer.cs file.

File.WriteAllBytes(@"C:\foobar.exe", Properties.Resources.foobar);

Add files to project resources and set their "Build Action" as "Embedded Resource".

Now extract any file (text or binary) using this snippet:

WriteResourceToFile("Project_Namespace.Resources.filename_as_in_resources.extension", "extractedfile.txt");


public static void WriteResourceToFile(string resourceName, string fileName)
{
    int bufferSize = 4096; // set 4KB buffer
    byte[] buffer = new byte[bufferSize];
    using (Stream input = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
    using (Stream output = new FileStream(fileName, FileMode.Create))
    {
        int byteCount = input.Read(buffer, 0, bufferSize);
        while (byteCount > 0)
        {
            output.Write(buffer, 0, byteCount);
            byteCount = input.Read(buffer, 0, bufferSize);
        }
    }
}

Don't know how deep is it correct according to this article: http://www.yoda.arachsys.com/csharp/readbinary.html but it works.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!