我使用以下代码动态加载cs文件:
CSharpCodeProvider codeProvider = new CSharpCodeProvider();
System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
//add referenced assemblies
parameters.ReferencedAssemblies.Add(...);
//filePath is a constant path.
parameters.OutputAssembly = filePath + ".dll";
CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, loadedFile);
if (results.Errors.Count > 0)
{
//error reporting
return;
}
else
{
//success reporting
}
byte[] assemblyBytes = File.ReadAllBytes(results.PathToAssembly);
Assembly AssemblyReference = Assembly.Load(assemblyBytes);
Type CompiledClass = AssemblyReference.GetType(/*some class in code*/);
InvokeStringMethod(CompiledClass, "Do_things", new object[] { /*some objects*/ });
只需单击一个按钮即可实现,多次单击时,文件编译成功并调用该方法。
但是,在将parameters.IncludeDebugInformation = true;
添加到编译器参数时,会在第一次成功编译该文件。但如果我再次尝试编译它,会发生以下错误:
"Unexpected error creating debug information file '<filepath>\\AAA.PDB' -- '<filepath>\\AAA.pdb: The process cannot access the file because it is being used by another process."
我搜索了这个问题并找到了这个解决方案: runtime code compilation gives error - process cannot access the file。但是,如果加载文件会将其锁定,为什么不包含调试信息时会出现此问题?不应该在所有情况下都发生这种情况吗?
答案 0 :(得分:0)
您链接到already has two answers by Hans Passant的问题。对我有用的是不分配给parameters.OutputAssembly
。