Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only load managed assembly DLLs in directory

Tags:

.net

asp.net

I need to load all the assemblies from DLLs in a directory.

My basic code is:

var assemblies = from filename in Directory.GetFiles(HttpRuntime.BinDirectory, "*.dll")
                 select Assembly.LoadFrom(filename);

However, if there are unmanaged DLLs in that directory then Assembly.LoadFrom fails. Is there a good way to only load the managed DLLs? Catching the load exception is an option, but I'd like to know if there's a better way.

My code runs on ASP.NET, at application start up. So I'll also accept an ASP.NET specific solution.

like image 521
Andrew Davey Avatar asked Aug 31 '11 13:08

Andrew Davey


2 Answers

Just loop through them separately and put the Assembly.LoadFrom in a try...catch block.

like image 101
Daniel A. White Avatar answered Nov 11 '22 04:11

Daniel A. White


from here: http://blogs.msdn.com/b/junfeng/archive/2004/02/06/68334.aspx

"Assembly.LoadFrom will throw BadImageFormatException if the given file is not a managed assembly.

This exception could be thrown for other reason as well. Suzanne kindly points out a more robust way. Once you catch the BadImageFormatException, look at its HResult field. If HResult is COR_E_ASSEMBLYEXPECTED, it means this is not a managed assembly."

Does that help?

like image 28
Tim Iles Avatar answered Nov 11 '22 06:11

Tim Iles