加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Windows > 正文

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

发布时间:2020-12-13 20:20:29 所属栏目:Windows 来源:网络整理
导读:检查DLL文件是Win32 DLL还是CLR程序集的最佳方式是什么?目前我使用这段代码 try { this.currentWorkingDirectory = Path.GetDirectoryName(assemblyPath); //Try to load the assembly. assembly = Assembly.LoadFile(assemblyPath); return assembly != nu
检查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标题:

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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读