【发布时间】:2017-01-23 21:29:34
【问题描述】:
我正在尝试使用 CSharpCodeProvider 动态编译代码。在引用的程序集中,我正在为 typeof(Program).Assembly.CodeBase) 添加一个引用参数,正如 here 所建议的那样,但它不起作用。我仍然收到错误提示
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() });
}
}
【问题讨论】:
-
尝试使用
typeof(Program).Assembly.Location而不是.CodeBase。程序集上的.Location属性将返回一条直线路径,而.CodeBase以 URI 形式返回位置。我不确定,但我认为可能存在与加载远程托管代码相关的情况,其中.Location没有给你任何东西,而.CodeBase可能会给你例如httpURI,但在您的场景中,听起来您的程序集始终是本地的,因此您应该始终具有有效的.Location值。 :-) -
完成,谢谢 :-)
-
谢谢!这有效 - 如果您添加为答案,我将标记为答案 - 并从 .CodeBase 检索到一个非常不同的路径 - CodeBase 检索了 bin 文件夹位置,而 Location 有一个临时目录:C:\\Windows\\Microsoft.NET \\Framework64\\v4.0.30319\\Temporary ASP.NET Files\\myIISDirName\\65307448\\ec575f43\\assembly\\dl3\\d46288d9\\3e71eb5a_c275d201\\MyProject.dll。这篇文章 (stackoverflow.com/questions/864484/…) 似乎暗示 .Location 在卷影复制之前提取地址,这让我对 Location 何时安全感到有些困惑......
标签: reference file-not-found csharpcodeprovider