Validating a .NET assembly in C #?

How do you check if an assembly is a loaded .NET assembly? I currently have this code, but an unmanaged DLL throws 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());
        }
+3
source share
8 answers

Can you just catch this exception?

Also see this article here: http://blogs.msdn.com/suzcook/archive/2004/03/17/determining-whether-a-file-is-an-assembly.aspx Just catch the exception. Validation will be much more expensive than just assuming the file is a valid assembly.

+11
source

, , PE . :

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 ());
}

, , Assembly.LoadFrom . , . .

+4

- .

, / , . , (32 64 ). .

.

, (, DLL ), , .

+2

. MSDN: , ( #)

+2

DLL .NET. "" . , .

+1

#, Try Catch.

peverify.exe, .net, , dll .

+1

Take a look at the Activator class .

Wrapping this method in a try / catch block can help you catch all sorts of invalid types, not just .NET assemblies, but also many other runtime violations.

-2
source

Source: https://habr.com/ru/post/1725064/


All Articles