Wednesday, September 10, 2008

Create .exe file from C# code

Wow! What a gr88 feature in .Net… Now you can create your own executable file directly on the runtime. Just supply the source code and create an .exe as you want it to be.

Here is the code snippet; I was surprised to see how easy it was.

Then just place this code in a Button Click event.

Microsoft.CSharp.CSharpCodeProvider cp = new Microsoft.CSharp.CSharpCodeProvider();
System.CodeDom.Compiler.ICodeCompiler ic = cp.CreateCompiler();
System.CodeDom.Compiler.CompilerParameters cpar = new System.CodeDom.Compiler.CompilerParameters();
string pathIcon = Application.StartupPath + "\\icon.ico";
cpar.CompilerOptions = "/target:winexe" + " " + "/win32icon:" + "\"" + pathIcon + "\"";
cpar.IncludeDebugInformation = false;
cpar.TreatWarningsAsErrors = false;
cpar.OutputAssembly = Application.StartupPath + "\\MyApplication.exe";
cpar.GenerateInMemory = false;
cpar.GenerateExecutable = true;
cpar.ReferencedAssemblies.Add("System.dll");
cpar.ReferencedAssemblies.Add("System.Windows.Forms.dll");
cpar.ReferencedAssemblies.Add("System.Drawing.dll");

//List all dll's to which your program would refer to.
string src = //C-Sharp source code (Or you can directly give the path of .cs file)
System.CodeDom.Compiler.CompilerResults cr = ic.CompileAssemblyFromSource(cpar, src.Trim());
foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors) MessageBox.Show(ce.ErrorText);


Here in the code, you can see that I have specified a path for an icon of my application “icon.ico”. You can just change the path and file name with your own file.
Also, same is with the application name “MyApplication.exe”; give what ever name you like :-)

That’s all! This way you can create your own application… Enjoy…
And yea, please do not forget to leave a comment on this post.

No comments:

Post a Comment