c# - 检查 DLL 文件是否是 C# 中的 CLR 程序集的最佳方法

标签 c# dll .net-assembly

检查 DLL 文件是 Win32 DLL 还是 CLR 程序集的最佳方法是什么。目前我使用这段代码

    try
    {
        this.currentWorkingDirectory = Path.GetDirectoryName(assemblyPath);

        //Try to load the assembly.
        assembly = Assembly.LoadFile(assemblyPath);

        return assembly != null;
    }
    catch (FileLoadException ex)
    {
        exception = ex;
    }
    catch (BadImageFormatException ex)
    {
        exception = ex;
    }
    catch (ArgumentException ex)
    {
        exception = ex;
    }
    catch (Exception ex)
    {
        exception = ex;
    }

    if (exception is BadImageFormatException)
    {
        return false;
    }

但我喜欢在加载前检查,因为我不想要那些异常(时间)。

有没有更好的办法?

最佳答案

检查 PE header :

DOS header starts at 0x0, the DWORD at 0x3c contains a pointer to the PE signature (usually 0x80) which is 4 bytes, the next 20 bytes is the COFF header and then there is the PE header (at 0x9. The PE header is 224 bytes and contains the data directory (at 96 bytes into the PE header = 0xf. The 15th entry (at 0x16 is the CLR header descriptor (sometimes called the COM descriptor, but this does not have anything to do with COM). If this is empty (ie 0 in the 8 bytes from 0x168 to 0x16f) then the file is not a .NET assembly. If you want to check if it is a COM DLL then you should look to see if it exports GetClassObject.

Ref.

更新:有一种更“.NET”的方法可以实现这一点:

使用Module.GetPEKind方法并检查 PortableExecutableKinds枚举:

NotAPortableExecutableImage The file is not in portable executable (PE) file format.

ILOnly The executable contains only Microsoft intermediate language (MSIL), and is therefore neutral with respect to 32-bit or 64-bit platforms.

Required32Bit The executable can be run on a 32-bit platform, or in the 32-bit Windows on Windows (WOW) environment on a 64-bit platform.

PE32Plus The executable requires a 64-bit platform.

Unmanaged32Bit The executable contains pure unmanaged code.

关于c# - 检查 DLL 文件是否是 C# 中的 CLR 程序集的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1366503/

相关文章:

c# - 使用移动相机检测运动

c# - IList实现测试

c# - 创建对 SQL Server C# 的查询

dll - 如何从 Jscript 文件加载 DLL 文件?

windows - 系统 DLL 地址空间

c# - 想要在部署的机器上使用 COM dll 文件而不注册 dll 文件

c# - 结构为 ReadOnlyMemory<byte> 表示

c# - GAC 中的装配安装

c# - 如何使用该库的所有引用添加对类库的引用?

c# - 如何正确加载程序集