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());
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With