@.тяµε.:
Indeed you may use Codedome! I also have an example for you. So let's create a new console app.
Ofcourse you can use WinForms but console app. suits better here just for now.
Now we need following namespaces added to our imports:
Code:
using System.CodeDom.Compiler;
using Microsoft.CSharp;
I suppose you have a test .cs file you want to compile, if not I wrote one for you.
Just open Notepad and save it as
Sample.cs or something:
Code:
using System;
namespace Program
{
public class MyProgram
{
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");
Console.ReadKey(true);
}
}
}
Now change back to your console app. project and add new method we
need later in order to compile our .cs file.
Code:
/// <summary>
/// Compiles the specified target.
/// </summary>
/// <param name="target">The target.</param>
/// <param name="outputFile">The output file.</param>
public static void Compile(string target, string outputFile)
{
// Add your references here.
//
string[] references = new[] {
"System.dll"
};
var parameters = new CompilerParameters()
{
OutputAssembly = outputFile,
GenerateExecutable = true,
TreatWarningsAsErrors = true,
CompilerOptions = "/optimize"
};
parameters.ReferencedAssemblies.AddRange(references);
var compiler = new CSharpCodeProvider();
var result =
compiler.CompileAssemblyFromFile(parameters, target);
if (result.Errors.HasErrors)
{
var output = "Failed to compile: ";
foreach (var error in result.Errors)
{
output += error.ToString();
}
throw new ApplicationException(output);
}
}
Now call it just like this:
Code:
Compile("Sample.cs", "Something.exe");
where
Sample.cs your source file and
Something.exe your output file.
PS. Don't forget to catch exceptions. ;)
@EDIT:
If you want to compile multiple files then change the target parameter type in my method to string[].
Now call it like this:
Code:
var targets = new[] {
"Sample.cs", // Main class that calls all subclasses.
"Class1.cs",
"Class2.cs"
};
Compile(targets, "Something.exe");
OR
Code:
Compile(new[] { "Sample.cs", "Class1.cs", "Class2.cs" }, "Something.exe");
Best regards,
Demon-777