public static bool CompileExecutable(String sourceName)
{
// Файл который вы скомпилировать
FileInfo sourceFile = new FileInfo(sourceName);
CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
// Создаем логическую переменную чтобы увидеть, были ли ошибки при компиляции
bool compileOk = false;
//Создаем имя будущего исполняемого файла
String exeName = String.Format(@"{0}{1}.exe",
System.Environment.CurrentDirectory, sourceFile.Name.Replace(".", "_"));
//Создаем переменную cp, чтобы задать параметры компилятора
CompilerParameters cp = new CompilerParameters();
//Вы можете скомпилировать как dll так и exe фай. Мы будем компилировать exe файл, поэтому выставляем компилятору true
cp.GenerateExecutable = true;
//Указываем будущего файла
cp.OutputAssembly = exeName;
//Save the exe as a physical file
cp.GenerateInMemory = false;
//Set the compliere to not treat warranings as erros
cp.TreatWarningsAsErrors = false;
//Make it compile
CompilerResults cr = provider.CompileAssemblyFromFile(cp, sourceName);
//if there are more then 0 erros...
if (cr.Errors.Count > 0)
{
//A message box shows the erros that occured
MessageBox.Show("Errors building {0} into {1}" +
sourceName + cr.PathToAssembly);
//for each error that occured in the code make a separete message box
foreach (CompilerError ce in cr.Errors)
{
MessageBox.Show(" {0}" + ce.ToString());
}
}
//Если нет ошибок, выводим сообщение
else
{
//Выводим сообщение об успешной компиляции
MessageBox.Show("Source {0} built into {1} successfully." +
sourceName + cr.PathToAssembly);
}
//Проверка были ли ошибки при компиляции
if (cr.Errors.Count > 0)
{
compileOk = false;
}
//if there are no erros...
else
{
compileOk = true;
}
//сообщаем об успешном выполнении компиляции
return compileOk;
}
Вызов функции:
private void button1_Click_1(object sender, EventArgs e)
{
//Создаем и записываем в файл .cs необходымый для компиляции код
TextWriter writer = new StreamWriter(Application.StartupPath + "\myExe.cs");
writer.WriteLine("using System;");
writer.WriteLine("using System.Collections.Generic;");
writer.WriteLine("using System.Text;");
writer.WriteLine("namespace TestAppi");
writer.WriteLine("{");
writer.WriteLine("class Program");
writer.WriteLine("{");
writer.WriteLine("static void Main(string[] args)");
writer.WriteLine("{");
writer.WriteLine("Console.WriteLine("Hello World");");
writer.WriteLine("Console.ReadLine();");
writer.WriteLine("} } }");
//Закрываем поток записи в файл и сохраняем его
writer.Close();
string file = Application.StartupPath + "\myExe.cs";
//Компиляция
CompileExecutable(file);
}
0.00 (0%) 0 votes











