Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validation of .NET assemblies in C#?

How do you check if a assembly loaded is a valid .NET assembly? I currently have this code but unmanaged DLL's throw a BadImageFormatException.

string[] filepaths = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.dll", SearchOption.AllDirectories);
List<Type> potentialEffects = new List<Type>();

foreach (string filepath in filepaths)
{
    Assembly a = Assembly.LoadFile(filepath);
    potentialEffects.AddRange(a.GetTypes());
}
like image 493
Euclid Avatar asked Dec 02 '22 06:12

Euclid


2 Answers

You could simply catch this exception?

Also see this article here: https://learn.microsoft.com/en-us/archive/blogs/suzcook/determining-whether-a-file-is-an-assembly
Just catch the exception. Checking would be a lot more costly than just assuming that a file is an valid assembly.

like image 157
Sebastian P.R. Gingter Avatar answered Dec 04 '22 10:12

Sebastian P.R. Gingter


I have this piece of code to check whether a file is a PE file and a managed assembly. It's quite easy to use:

var files = Directory.GetFiles (
    Directory.GetCurrentDirectory (),
    "*.dll", SearchOption.AllDirectories);

var potentialEffects = new List<Type> ();

foreach (var file in files) {
    if (!Image.IsAssembly (file))
        continue;

    var assembly = Assembly.LoadFile (filepath);
    potentialEffects.AddRange (assembly.GetTypes ());
}

For what it's worth, a little benchmark shows that it's twice as fast on my machine compared to the exception Assembly.LoadFrom will trigger. On the other hand, it will lose a bit of time in the valid case. So it's a matter of timing the average case.

like image 42
Jb Evain Avatar answered Dec 04 '22 11:12

Jb Evain