0

我正在尝试使用 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() });
            }
        }
4

1 回答 1

2

尝试使用typeof(Program).Assembly.Location而不是.CodeBase. 程序集上的.Location属性将返回加载的实际文件的直接路径,而.CodeBase以 URI 形式返回正则位置。我不确定,但我认为可能存在与加载远程托管代码相关的场景,其中.Location不会给你任何东西,.CodeBase可能会给你一个httpURI,但在你的场景中,听起来你的程序集总是在本地,所以你应该总是有一个有效的.Location价值。:-)

于 2017-01-23T22:22:36.067 回答