c# - 程序集文件重命名和 Assembly.LoadFile

标签 c# file-io clr .net-assembly

情况是这样的:

我有一个名为 Lib1.dll 的程序集。出于某种原因(与问题无关)我不得不将程序集文件名重命名为 Lib1New.dll,现在在尝试使用 Assembly.LoadFile 加载重命名的程序集时我注意到 CLR 也尝试加载 Lib1.dll。

如果在搜索路径中找到 Lib1.dll,它将加载到地址空间中。无论是否找到 Lib1.dll,应用程序都可以正常工作。 (问题是,如果发现 Lib1.dll,文件将被锁定,其他进程无法删除)。

enter image description here

我不明白为什么 LoadFile 会搜索并加载 Lib1.dll。 LoadFile 应该加载指定位置的程序集文件的内容,为什么它要搜索文件。

LoadFile 的 MSDN 文档:

Use the LoadFile method to load and examine assemblies that have the same identity, but are located in different paths. LoadFile does not load files into the LoadFrom context, and does not resolve dependencies using the load path, as the LoadFrom method does. LoadFile is useful in this limited scenario because LoadFrom cannot be used to load assemblies that have the same identities but different paths; it will load only the first such assembly.

最佳答案

我建议您尝试简化您的问题,因为我只是尝试重现您的情况并且没有遇到任何问题。我创建了一个 Lib.dll 程序集,编译它,创建了一个控制台应用程序,用 LoadFile 加载它,然后将 Lib.dll 和控制台对它的引用重命名为“LibNew.dll”。然后我重新编译 lib.dll 并运行控制台应用程序。那时我无法删除 LibNew.dll,但我能够删除 Lib.dll。

我怀疑你的 Lib.dll 可能在启动时从它自己的程序集中加载一些信息,并且在内部使用另一个 Load 函数来这样做,最终找到原始的 Lib.dll。但是,如果您有一个非常简单的 DLL,它就不会增加额外的负载。我的 DLL 有一个函数,我可以调用它,但我仍然看到上面报告的结果。这是我的代码:

控制台应用程序:

class Program
{
    static void Main(string[] args)
    {
        System.Reflection.Assembly assy = System.Reflection.Assembly.LoadFile(args[0]);
        Type class1 = assy.GetType("Lib.Class1");

        System.Reflection.MethodInfo myMethod = class1.GetMethod("MyMethod");
        Console.WriteLine(myMethod.Invoke(null, new object[] {"This is a string"}).ToString());

        Console.ReadLine();
    }
}

库:

namespace Lib
{
public class Class1
{
    public static string MyMethod(string param)
    {
        return "Fixed: [" + param.Replace(" ", "-") + "]";
    }
}
}

仅监控 LoadImage 调用,我发现它没有尝试加载 Lib.dll: Process Monitor Trace of LoadImage calls

但是,通过监控所有事件,我发现它确实 探测了应用程序目录中的 Lib.dll。 Process Monitor Trace of all references to Debug\Lib

也许如果您将 DLL 放在另一个目录中,您可以强制执行您想要的行为?不过,考虑到文档,这是一种奇怪的行为。

关于c# - 程序集文件重命名和 Assembly.LoadFile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5679521/

相关文章:

c# - ASP :GridView HYPERLINKFIELD - asp code inside datanavigateurlformatstring

c# - 如何获取多个<a>标签的内文?

c++ - fstream.write() 的 std::ios::failue (ios::badbit) 问题

c - 如何读取单行

python - 将二进制数据视为文件对象?

.net - 沃森桶 P1

c# - 将数据从 C# 程序发送到 Arduino

c# - 什么时候是 sqlchars 什么时候是 sqlstring?

.net - Sqlite 数据类型映射到 .net (CLR) 框架数据类型

c# - Msdn风格地址URL本地化可能实现