Lets jump in to coding. The namespaces that we are going to use in this project are
- System.CodeDom
- System.CodeDom.Compiler
- Microsoft.CSharp
The Microsoft.CSharp namespace contains classes that support compilation and code generation using the C# language.
At first we need to instantiate the class CSharpCodeProvider. Then create a complier using CreateCompiler() function of CSharpCodeProvider class and assign to the interface ICodeCompiler.
CSharpCodeProvider codeProvider = new CSharpCodeProvider();
ICodeCompiler icc = codeProvider.CreateCompiler();
Then set the parameters for the compiler using CompilerParameters class. Set parameters like GenerateExecutable, OutputAssembly
System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
parameters.GenerateExecutable = true;
parameters.OutputAssembly = "Out.exe";
Now declare a String variable and write the source code for the new application/program. Now instantiate CompilerResults class with compiler parameters and the source code as below.
String sourcecode;
sourcecode="using System;namespace SampleApp{class Class1{[STAThread] static void Main(string[] args) { Console.WriteLine(\"I am born to live!\");Console.Read(); } }}";
CompilerResults results = icc.CompileAssemblyFromSource(parameters,sourcecode);
Now the code is compiled. If you want to run the compiled EXE, start the process by
Process.Start("Out.exe");
Thats all folks!....
Happy coding
1 comment:
Good Article Thiagarajan!!
To find .Net faqs you can visit
Microsoft.NET Framework 2.0 Class Library Namespaces
Post a Comment