VB.Net - 检查文件是否为.net二进制文件

时间:2014-03-06 22:09:01

标签: c# vb.net file native managed

如果文件

,我如何检查VB.Net
  

C:\文件\将Test.exe

是.net二进制文件还是原生二进制文件?

2 个答案:

答案 0 :(得分:7)

How to: Determine If a File Is an Assembly (C# and Visual Basic)上的MSDN:

  

如何以编程方式确定文件是否为程序集

     
      
  1. 调用GetAssemblyName方法,传递您正在测试的文件的完整文件路径和名称。
  2.   
  3. 如果抛出BadImageFormatException异常,则该文件不是程序集。
  4.   

它甚至有一个VB.NET示例:

Try 
    Dim testAssembly As Reflection.AssemblyName =
                            Reflection.AssemblyName.GetAssemblyName("C:\Windows\Microsoft.NET\Framework\v3.5\System.Net.dll")
    Console.WriteLine("Yes, the file is an Assembly.")
Catch ex As System.IO.FileNotFoundException
    Console.WriteLine("The file cannot be found.")
Catch ex As System.BadImageFormatException
    Console.WriteLine("The file is not an Assembly.")
Catch ex As System.IO.FileLoadException
    Console.WriteLine("The Assembly has already been loaded.")
End Try

这并不理想,因为它使用控制流的异常。

我也不确定它在角落的情况下是如何表现的,例如文件是程序集,但不支持当前的CPU体系结构,或者它是否针对不支持的框架变体。

答案 1 :(得分:0)

我正在编写一个通用的用法函数来补充@Loki答案:

''' <summary>
''' Determines whether an exe or dll file is an .Net assembly.
''' </summary>
''' <param name="File">Indicates the exe/dll file to check.</param>
''' <returns><c>true</c> if file is an .Net assembly, <c>false</c> otherwise.</returns>
Friend Function FileIsNetAssembly(ByVal [File] As String) As Boolean

    Try
        System.Reflection.AssemblyName.GetAssemblyName([File])
        ' The file is an Assembly.
        Return True

    Catch exFLE As IO.FileLoadException
        ' The file is an Assembly but has already been loaded.
        Return True

    Catch exBIFE As BadImageFormatException
        ' The file is not an Assembly.
        Return False

    End Try

End Function
相关问题