简体   繁体   中英

Embed a file into an external exe with C#

So I've made an interpreted programming language, and everything is going fine except one thing: I want to make a "compiler" that will embed the user's code into a copy of the interpreter, that way all the user needs to do is double click the executable with the code embedded into it and it would run.

So the question is: how can I embed a file into an already compiled executable? I do have access to the executable before it's compiled, but the embedding process must happen after.

I would prefer the solution to be in C# but I'm desperate and could use C++ or VB.NET, or even a batch file

So after some intense googling I found a library called Mono.Cecil which does exactly what I want. I was able to inject a file into an executable file by using the following code:

string fileName = "Interpreter.exe"; // The file which will have toInject injected in it
string outputName = "Compiled.exe";  // The output file to compile
string toInject = "program.txt";     // The file we will be injecting into fileName
string resourceName = "program.txt"; // The name of the file once it's inside fileName

var module = ModuleDefinition.ReadModule(filename);

var file = new EmbeddedResource(
    resourceName,
    ManifestResourceAttributes.Private,
    File.ReadAllBytes(toInject));

module.Resources.Add(file);

module.Write(outputName);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM