Compilation of file in code
-
How can you compil a .cs file in the code? Not using the command line.
-
We need to use the class.
CSharpCodeProvider
as well as types of spaceSystem.CodeDom.Compiler
:using Microsoft.CSharp; using System.CodeDom.Compiler;
...
// компилятор
var codeProvider = new CSharpCodeProvider();
ICodeCompiler compiler = codeProvider.CreateCompiler();// параметры компиляции
var parameters = new CompilerParameters()
{
// указываем, что генерируем исполняемый файл (exe)
GenerateExecutable = true,
// если хотим сохранить на диск
OutputAssembly = "...",
// если хотим сохранить в памяти
// (хотя файл все равно cгенерируется во временной директории)
//GenerateInMemory = true
};// компилируем
var source = File.ReadAll("SomeFile.cs");
CompilerResults results = compiler.CompileAssemblyFromSource(parameters, source);// проверяем, есть ли ошибки
if (results.Errors.Count > 0)
{
foreach (CompilerError error in results.Errors)
{
Console.WriteLine($"Line number {error.Line}, error number {error.ErrorNumber}: {error.ErrorText}");
}
}// если нужно обратиться к скомпилированной сборке,
// используйте свойство results.CompiledAssembly