Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if dll is .net library "The module was expected to contain an assembly manifest."

How can I verify if dll was wrote in .net? I'm using code as below:

Assembly assembly = null;
try
{    
   foreach (string fileName in Directory.GetFiles(Environment.CurrentDirectory.ToString(), "*.dll", SearchOption.TopDirectoryOnly))
   {
     try
     {
        assembly = Assembly.LoadFrom(fileName);
        Console.WriteLine(fileName);
     }
     catch (Exception ex)
     {
       ...               
     }
     finally
     {
       ...
     }
    }              
}
catch (ReflectionTypeLoadException ex)
{
  ..              
}

When I want to load assembly = Assembly.LoadFrom(fileName) non-.net dll, an exception will appear:

Could not load file or assembly 'file:///...' or one of its dependencies. The module was expected to contain an assembly manifest.

I want to use verify in if-else clause. Can you help me?

like image 925
Robert Avatar asked Nov 23 '25 03:11

Robert


1 Answers

There's a helper function in the .NET bootstrapper DLL that you can use. Mscoree.dll exports GetFileVersion(), a helper that returns the CLR version that an assembly needs. That function is going to fail when the file isn't an assembly and does so without raising an exception.

It should look like this:

using System;
using System.Text;
using System.Runtime.InteropServices;

public class Utils {
    public static bool IsNetAssembly(string path) {
        var sb = new StringBuilder(256);
        int written;
        var hr = GetFileVersion(path, sb, sb.Capacity, out written);
        return hr == 0;
    }

    [DllImport("mscoree.dll", CharSet = CharSet.Unicode)]
    private static extern int GetFileVersion(string path, StringBuilder buffer, int buflen, out int written);
}
like image 125
Hans Passant Avatar answered Nov 24 '25 18:11

Hans Passant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!