【问题标题】:Missing Added Reference When Using CodeDom Compiler使用 CodeDom 编译器时缺少添加的参考
【发布时间】:2017-09-28 11:27:59
【问题描述】:

我发现了与此类似的问题,但还没有找到专门解决我的问题的东西。

我有一些通过System.CodeDom.Compiler 编辑Excel 工作簿的代码。这很重要,因为我希望以后能够为不同的工作簿“插入”不同的编辑指令。

在 Visual Studio 中使用 References>Add... 将 Microsoft.Office.Interop.Excel.Dll 的引用添加到我的项目中,并且我使用 .ReferencedAssemblies.Add 为 CodeDom 编译器添加了 excel dll 的引用,如下所示:

CSharpCodeProvider provider = new CSharpCodeProvider(providerOptions);

CompilerParameters compilerParams = new CompilerParameters();
compilerParams.GenerateInMemory = true;
compilerParams.GenerateExecutable = false;
compilerParams.ReferencedAssemblies.Add("System.Windows.Forms.Dll");
compilerParams.ReferencedAssemblies.Add("Microsoft.Office.Interop.Excel.Dll");

但不幸的是,出现了这个错误:

{错误 CS0006:找不到元数据文件“Microsoft.Office.Interop.Excel.Dll”}

有什么简单的方法可以告诉 CodeDom 编译器找到这个 dll 吗?

我曾尝试将compilerParams.ReferencedAssemblies.Add(typeof(Microsoft.Office.Interop.Excel.Application).Assembly.Location); 设为suggested elsewhere,但这仅指向编译后的程序exe,而不是所需的dll。

谢谢,乔。

【问题讨论】:

  • 我正在为类似的问题而苦苦挣扎,不希望这是解决方案,但您是否尝试过小写的“.dll”结尾? (对我来说,加载 System.Data 有效,但仅在 VS(调试和发布)中,构建的 host-exe 只是找不到 dll ......无论如何...... -.- )
  • 这是一个好点 - 我不得不承认,我没有尝试小写文件扩展名。自从从事这项工作以来,我一直受到严重的旁注,但如果我回到它 - 我一定会试一试!如果它不起作用,我也会在这里反馈,我会找到替代解决方案。谢谢 :)

标签: c# dll system-codedom-compiler


【解决方案1】:

这可能不是答案,但对于评论来说太多了,并且可以作为“解决方法”提供帮助。

我设法加载了不属于托管程序集的 System.Data.dll。我手动将它放在正在执行的“bin”文件夹中,只是为了测试。 我使用的错误很明显:

String pathToDll = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;

获取该dll的基本目录。但我有一个 uri (file:///C:/...)。一旦解析为“C:\ ...”,一切顺利。

由于找不到您的 dll,您可以编辑该引用的属性并设置“CopyLocal = true”,以便 dll 最终与 .exe 位于同一路径中。之后您应该能够加载它:

String pathAndFile = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;    
pathAndFile = Path.GetDirectoryName(pathAndFile);
Uri uri = new Uri(pathAndFile);
pathAndFile = uri.LocalPath + "\\" + "Microsoft.Office.Interop.Excel.Dll";
compilerParams.ReferencedAssemblies.Add(pathAndFile);

另外,看看这段代码,它应该从宿主程序集中加载所有内容。 (警告:您不能在同一个 AppDomain 中两次加载单个程序集)

var assemblies = AppDomain.CurrentDomain
                       .GetAssemblies()
                       .Where(a => !a.IsDynamic)
                       .Where(a => !parameters.ReferencedAssemblies.Contains(a.Location))
                       .Select(a => a.Location);

parameters.ReferencedAssemblies.AddRange(assemblies.ToArray());

据我阅读,这两个教程有点旧(代码被贬低),但帮助我理解了更多:

https://west-wind.com/presentations/DynamicCode/DynamicCode.htm https://weblog.west-wind.com/posts/2016/Dec/12/Loading-NET-Assemblies-out-of-Seperate-Folders

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 2011-05-10
    • 2020-02-24
    相关资源
    最近更新 更多