Scanning DLLs for .NET collections with a specific interface - some DLL files throw R6034!

I have a program that should detect plugin DLL modules on its host.

He does this by listing all the DLLs in the path (quite large). This path includes many things, including your own DLLs.

foreach (var f in Directory.EnumerateFiles(@"c:\Program Files", "*.dll", SearchOption.AllDirectories)) { try { var assembly = Assembly.LoadFile(f); var types = assembly.GetTypes(); foreach (var type in types) { if (type.GetInterface("My.IInterface") != null) { plugins.Add(f); break; } } assembly = null; } catch (Exception e) { } } 

If my scanner enters the MS runtime DLL (for example, msvcm80.dll), I get an unrecoverable R6034 runtime error: "The application tried to load the C runtime library incorrectly." This window blocks the execution of the program. I do not want this DLL (obviously); is there any way to get an elegant error from this situation?

[Related q: is there an efficient (for example, no exception) way to determine if a DLL is a .NET assembly or not if that DLL is not currently loading into the process space?]

+7
source share
2 answers

First do the reflection load only with Assembly.ReflectionOnlyLoadFrom . Only after you find the plugin in the assembly should you fully load it using Assembly.LoadFrom .

To answer another question, you can check if the file has a CLR header.

See this post “Reading the CLR Header” on mpdotnet.framework

Together, they should allow you to avoid any exceptions and error messages when searching for plugins.

+10
source

It doesn't seem like a good idea in \ Program Files ... Can anyone post malicious DLLs?

Have you looked at MEF ? It can be a little safer, too.

There is a directory that will automatically download assemblies for you and return an array of your interface to you.

Not sure if you are familiar with Injection Dependency Injection or (IoC) Inversion of Control, but you can also use MEF.

It is included in .Net 4.0.

+2
source

All Articles