C# 使用CodeProvider将许多外部.cs文件编译成.dll

C# 使用CodeProvider将许多外部.cs文件编译成.dll,c#,C#,我正在尝试编写一个程序,可以将用户生成的.cs文件编译到库中供以后使用(实际上只是为了防止下次程序启动时重新编译它们)。当我试图将它们编译成.dll时,我得到一个错误,表示该文件正被另一个程序使用 以下是我的实现: CompilerParameters params = new CompilerParameters(); params.GenerateExecutable = false; params.GenerateInMemory = false; params.OutputAssembl

我正在尝试编写一个程序,可以将用户生成的.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.
为什么它会给我这个错误?如果要向程序集添加许多类,是否需要以不同的方式调用编译器


感谢您的帮助。

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

与其传递单个文件名info COMPILEASEMBLYFROMFILE,不如给它一个数组。像这样:

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

我认为,您需要为每个独立的cs更改params.OutputAssembly=“test.dll”param。