使用CodeProvider将许多外部.cs文件编译为.dll

时间:2015-08-22 16:28:19

标签: c#

我正在尝试编写一个程序,该程序可以获取用户生成的.cs文件并将它们编译到库中供以后使用(实际上只是为了防止在下次程序启动时重新编译它们)。当我尝试将它们编译成.dll时,我收到一条错误消息,说该文件正被另一个程序使用。

这是我的实施:

CompilerParameters params = new CompilerParameters();
params.GenerateExecutable = false;
params.GenerateInMemory = false;
params.OutputAssembly = "test.dll";
params.TreatWarningsAsErrors = true;

CSharpCodeProvider provider = new CSharpCodeProvider();

DirectoryInfo di = DirectoryInfo di = new DirectoryInfo(path);
FileInfo[] files = di.GetFiles("*.cs", SearchOption.AllDirectories);
foreach(FileInfo fi in files)
{
    CompilerResults cr = provider.CompileAssemblyFromFile(params, fi.FullName);
    if(cr.Errors.Count > 0)
    {
        foreach(CompilerError ce in cr.Errors)
        {
            Console.WriteLine(ce.ToString());
        }
    }
}

第一个文件编译得很好。不过,之后的每个文件都会给我这个错误:

CS0016: Cannot write to output file "temp.dll" -- The process cannot access the file because it is being used by another process.

为什么它会给我这个错误?如果我打算向程序集中添加许多类,是否需要以不同的方式调用编译器?

感谢您的帮助。

1 个答案:

答案 0 :(得分:-1)

CodeProvider类可以将多个文件一次编译到程序集中。

不是传递单个文件名信息CompileAssemblyFromFile,而是给它一个数组。像这样:

string[] files = { "a.cs", "b.cs", "c.cs" };
sCodeProvider.CompileAssemblyFromFile(sCompilerParams, files);
相关问题