我正在尝试使用 CSharpCodeProvider 动态编译代码。在引用的程序集中,我正在为 typeof(Program).Assembly.CodeBase) 添加一个引用参数,正如这里所建议的那样,但它不起作用。我仍然收到一条错误消息
error CS0006: Metadata file 'file:///C:/Code/MyProject/bin/MyProject.DLL' could not be found;
该名称的文件确实存在 - 唯一的区别是文件扩展名在文件资源管理器(“.dll”)中显示为小写,但除此之外,错误消息中的文件名与我要引用的 dll 的名称和路径匹配。
知道为什么编译器在这种情况下看不到引用的 dll 吗?
这是我的代码的相关部分:
CompilerResults result = null;
CompilerParameters parms = new CompilerParameters();
parms.GenerateExecutable = false;
parms.GenerateInMemory = true;
parms.OutputAssembly = "MyOutputAssembly";
parms.ReferencedAssemblies.Add("System.dll");
parms.ReferencedAssemblies.Add("System.Data.dll");
parms.ReferencedAssemblies.Add("mscorlib.dll");
parms.ReferencedAssemblies.Add(typeof(Program).Assembly.CodeBase); // Reference the current assembly
// Lock because CSharpCodeProvider can only compile the code once per time slot
lock (lockCompile)
{
using (CSharpCodeProvider codeProvider = new CSharpCodeProvider())
{
result = codeProvider.CompileAssemblyFromSource(parms, new string[] { code.ToString() });
}
}