【问题标题】:Loading ResourceManager from separate assembly produces FileNotFound?从单独的程序集中加载 ResourceManager 会产生 FileNotFound?
【发布时间】:2013-08-08 18:16:05
【问题描述】:

我有一个程序集,我试图通过反射加载并从中读取资源字符串。

所以,我使用这样的东西:

        config.Extras="C:\dev\foo.dll";
        string dir = Directory.GetCurrentDirectory();
        string tmp = Path.GetDirectoryName(config.Extras[0]);
        Directory.SetCurrentDirectory(tmp);
        var asm = Assembly.LoadFile(config.Extras[0]);
        foreach (var item in asm.GetManifestResourceNames())
        {
                ResourceManager rm = new ResourceManager(item, asm);
                string foo=rm.GetString("foo"); //error here
        }

但是,这会引发 FileNotFoundException,因为它找不到 foo.dll 的引用程序集。 Foo.dll 依赖于Bar.dll。它抛出错误说它找不到bar.dllbar.dll 的实际位置与 foo.dll 在同一目录中。

那么,我该如何解决这个错误呢?

【问题讨论】:

  • 永远不要使用 LoadFile(),加载的程序集没有加载上下文。使用 LoadFrom()。
  • @HansPassant 修复了它。如果你比一个答案,我会接受它。呵呵

标签: c# reflection filenotfoundexception resourcemanager


【解决方案1】:

Assembly 类中的 Load 方法存在命名问题。没有人会弄错 Load()。但是 LoadFile() 有一个 much 太吸引人的名字。 LoadFrom 应该是 LoadFile,LoadFile 应该是 LoadButUseThisOnlyWhenYouReallyKnowWhatItDoes()。

程序集的加载上下文很难理解。 Suzanne Cooke 已经在博客上写了很多关于它的文章,但并没有过多地解释它 :) 粗略地说,当您使用 LoadFile 时,CLR 不会跟踪程序集的来源,也不会阻止您加载程序集不止一次。该程序集中的类型是唯一的,并且从两个 LoadFile 调用加载的相同类型不相同。只有当您有意不想匹配时,您才使用 LoadFile。读取元数据的程序会感兴趣的东西,例如反编译器。

“不跟踪程序集的来源”子句是这里的问题。您需要使用 LoadFrom()。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多