The following is a C # compiler written by a foreign user. Of course, it is still used. net FCL, so it is impossible to be a true compiler. I will introduce the flying knife to let everyone get rid of the csc constraints and complete the compilation on the Win interface.
You must complete the following steps:
1. Create a CSharpCodeProvider instance (VBCodeProvider is used if Visual Basic is used)
2. Included interface ICodeCompiler
3. Provide CompilerParameters Parameters
4. compile using the CompileAssemblyFromSource method.
5. Run CompilerResults
6. Execute the compiled program
The compiled code can be a string written in a text box, or a source file.
The following is the source code:) I will modify the source code in two days and then provide the entire source code :)
Private void button#click (object sender, System. EventArgs e)
{
CSharpCodeProvider codeProvider = new CSharpCodeProvider ();
// For Visual Basic Compiler try this:
// Microsoft. VisualBasic. VBCodeProvider
ICodeCompiler compiler = codeProvider. CreateCompiler ();
CompilerParameters parameters = new CompilerParameters ();
Parameters. GenerateExecutable = true;
If (appName. Text = "")
{
System. Windows. Forms. MessageBox. Show (this,
"Application name cannot be empty ");
Return;
}
Parameters. OutputAssembly = appName. Text. ToString ();
If (mainClass. Text. ToString () = "")
{
System. Windows. Forms. MessageBox. Show (this,
"Main Class Name cannot be empty ");
Return;
}
Parameters. MainClass = mainClass. Text. ToString ();
Parameters. IncludeDebugInformation = includeDebug. Checked;
// Add available assemblies-this shoshould be enough for the simplest
// Applications.
Foreach (Assembly asm in AppDomain. CurrentDomain. GetAssemblies ())
{
Parameters. ReferencedAssemblies. Add (asm. Location );
}
String code = textBox1.Text. ToString ();
// System. Windows. Forms. MessageBox. Show (this, code );
CompilerResults results = compiler. CompileAssemblyFromSource (parameters,
Code );
If (results. Errors. Count> 0)
{
String errors = "Compilation failed :";
Foreach (CompilerError err in results. Errors)
{
Errors + = err. ToString () + "";
}
System. Windows. Forms. MessageBox. Show (this, errors,
"There were compilation errors ");
}
Else
{
# Region Executing generated executable
// Try to execute application
Try
{
If (! System. IO. File. Exists (appName. Text. ToString ()))
{
MessageBox. Show (String. Format ("Cant find {0}", appName ),
"Cant execute.", MessageBoxButtons. OK,
MessageBoxIcon. Error );
Return;
}
ProcessStartInfo pInfo = new ProcessStartInfo (appName. Text. ToString ());
Process. Start (pInfo );
}
Catch (Exception ex)
{
MessageBox. Show (String. Format ("Error while executing {0 }",
AppName) + ex. ToString (), "Cant execute .",
MessageBoxButtons. OK, MessageBoxIcon. Error );
}
# Endregion
}
}