1

I'm compiling a C# assembly at runtime within my program using CSharpCodeProvider, which depends on a few libraries which are built as .dlls, and also the program that's building it.

I'd ideally like to only build one executable, and not have to copy around all the dependencies with it.

Here's the code I'm using to compile the assembly:

//Create the compiler (with arguments).
CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerParameters cp = new CompilerParameters();
cp.GenerateExecutable = true;
cp.OutputAssembly = "example.exe";
cp.GenerateInMemory = false;

//Reference the main assembly (this one) when compiling.
Assembly entryasm = Assembly.GetEntryAssembly();
cp.ReferencedAssemblies.Add(entryasm.Location);

//Reference an external assembly it depends on.
cp.ReferencedAssemblies.Add("someExternal.dll");

//Attempt to compile.
CompilerResults results = provider.CompileAssemblyFromSource(cp, someScript);

The executable this produces still needs someExternal.dll and the program that built it in the same directory when run, and I'd prefer it to be a single executable with all dependencies included.

Is there any way to do this?

1 Answer 1

1

In the end, I ended up using the ILRepack.Lib NuGet package for the job, which allows you to merge binaries programmatically, without using a command line tool.

Here's the code I'm using to pack all .dll files in the directory into the executable:

//Setting required options.
RepackOptions opt = new RepackOptions();
opt.OutputFile = "example_packed.exe";
opt.SearchDirectories = new string[] { AppDomain.CurrentDomain.BaseDirectory, Environment.CurrentDirectory };

//Setting input assemblies.
string[] files = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.dll");
opt.InputAssemblies = new string[] { "example.exe", entryasm.Location }.Concat(files).ToArray();

//Merging.
ILRepack pack = new ILRepack(opt);
pack.Repack();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.