Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to try and catch assembly not found

Tags:

c#

.net

OK, say I have an application like this:

using System;
using AliensExist; // some DLL which can't be found...

What I want is that if the assembly DLL AlienExist can't be found the application won't return an error - but rather be "trycatched" that is something like...:

using System;
try{
using AliensExist; // some DLL which can't be found...
} catch {}

How to do it? I know the using keyword can't be used later...but i am way too lazy now to test it.

10x!

like image 731
johny Avatar asked Mar 04 '11 19:03

johny


2 Answers

Old question, but I feel this info needs added:

You can't try/catch a using statement, but you can try/catch the resolving of an assembly.

You have even more control if you manually load assemblies as suggested by Mike Atlas.

Also, you can manually verify an assembly before attempting to resolve by selecting from GetEntryAssembly.GetReferencedAssemblies() and comparing against something like AssemblyName.GetAssemblyName().

Of course, you can use a simple File.Exists(AssemblyPath) in some cases, but the methods above would help verify additional assembly issues, such as version numbering or signing.

AssemblyResolve is nice by offering an event based approach. Good if you've got high cyclomatic complexity and/or want to ride along with JIT, but less informative than an upfront verification.

Be mindful of the fail-fast principal, and the extent to which assembly resolve errors may limit functionality.

like image 107
u8it Avatar answered Oct 08 '22 11:10

u8it


You can't really do that in a try/catch, but what you can do is handle the AssemblyResolve event on the AppDomain.

See http://msdn.microsoft.com/en-us/library/system.appdomain.assemblyresolve.aspx for further details.

However, you will at least need to get your code compiling. If you are trying to "reference" an assembly which may or may not exist, you will need to dynamically load it and work from there.

like image 43
vcsjones Avatar answered Oct 08 '22 11:10

vcsjones