Search code examples
c#vb.netfilenativemanaged

VB.Net - Check if File is .net binary


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?


Solution

  • 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.