2015-08-22 49 views
-1

我正在尝试编写一个程序,该程序可以将用户生成的.cs文件编译为一个库供以后使用(实际上只是为了防止重新编译它们下次程序启动时)。当我尝试将它们编译为.dll文件时,我收到一条错误消息,指出该文件正在被另一个程序使用。使用CodeProvider将许多外部.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. 

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

感谢您的帮助。

+0

我想,你需要改变params.OutputAssembly =“test.dll”参数为每个独立的CS。 – mkysoft

回答

-1

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

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

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