Domanda

How can I check with VB.Net if a the file

C:\Documents\Test.exe

is a .net binary or if it is a native binary?

È stato utile?

Soluzione

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

How to programmatically determine if a file is an assembly

  1. Call the GetAssemblyName method, passing the full file path and name of the file you are testing.
  2. If a BadImageFormatException exception is thrown, the file is not an assembly.

It even has an VB.NET example:

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

This isn't ideal since it uses exceptions for control flow.

I'm also not sure how it behaves in corner cases like the file being an assembly, but not supporting the current CPU architecture or if it targets an unsupported variant of the framework.

Altri suggerimenti

Just I've write a generic usage function to complement @Loki answer:

''' <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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top