How to check if a DLL and an exe is a .NET assembly

 
 
  • Gérald Barré

Recently, I needed to check if a file was a .NET assembly without loading the assembly. .NET uses the Portable Executable (PE) format to store assemblies. The PE format is a file format for executables or DLLs on Windows, but .NET also uses it on Linux and MacOS. Hopefully, .NET provides the PEReader class to read the file header. This class can parse the content of a file to extract PE information. You can also use the MetadataReader class to read the metadata of the assembly.

C#
static async Task<bool> IsDotNetAssembly(string fileName)
{
    await using var stream = File.OpenRead(fileName);
    return IsDotNetAssembly(stream);
}

static bool IsDotNetAssembly(Stream stream)
{
    try
    {
        using var peReader = new PEReader(stream);
        if (!peReader.HasMetadata)
            return false;

        // If peReader.PEHeaders doesn't throw, it is a valid PEImage
        _ = peReader.PEHeaders.CorHeader;

        var reader = peReader.GetMetadataReader();
        return reader.IsAssembly;
    }
    catch (BadImageFormatException)
    {
        return false;
    }
}

Note 1: In the case of .NET, the exe file is a native application (App Host). You can check if there is a DLL with the same name as the exe to find the associated .NET assembly.

Note 2: If you want to detect .NET application published as single file, you can check the code from ILSpy to see how to detect the bundle (SingleFileBundle).

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?Buy Me A Coffee💖 Sponsor on GitHub