开发者

Only load managed assembly DLLs in directory

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 acc开发者_JAVA技巧ept an ASP.NET specific solution.


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


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?


Some googling led me to this page: Detect if an assembly is a managed assembly . Sounds like this would be a great fit.

It really depends how many unmanaged dlls you expect and how sensitive you are about your startup time (I am assuming you're doing this on startup). If you can relax on both accounts, the try...catch surely is the simplest thing to do, otherwise, reading the assembly header information should be orders of magnitude quicker.


Call GetAssemblyName() and if it throws a BadImageFormatException, then it's not a Assembly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜