Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check that a referenced assembly is available at runtime?

Tags:

c#

I am creating a simple, standalone .net winforms app. It references the assembly Microsoft.SqlServer.SqlWmiManagement of .Net Framework 4 that may or may not be present on a client's machine. If that assembly is not present, then at run time I would like my app to fail gracefully and not crash.

I have a component that starts:

...
using Microsoft.SqlServer.SqlWmiManagement;
...
try {
    // do something that uses SqlWmiManagement
}
catch {
    // handle the missing assembly
}

Unfortunately, an unhandled exception is thrown as the component loads, way before my little try block.

What is the correct way to do this?

There's no installer, this should be a drag-and-drop exe.

like image 729
onupdatecascade Avatar asked Dec 11 '22 17:12

onupdatecascade


2 Answers

If an assembly is not found, then the AssemblyResolve event will fire. You can try catching that and exiting the app there. See this MSDN.

public static void Main()
{
    // Note: AssemblyResolve occurs when the resolution of an assembly fails.
    AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);
}

private static Assembly MyResolveEventHandler(object sender, ResolveEventArgs args)
{
    if ( args.Name.Contains("SqlWmiManagement"))
    {
        // assembly not found
    }

    return null;
}
like image 194
CC Inc Avatar answered Jun 03 '23 05:06

CC Inc


The exception is thrown when the function is JIT'd. Change your code to:

void DoSomethingThatUsesSqlWmiManagement_()
{
   ...
}
void DoSomethingThatUsesSqlWmiManagement()
{
   try
   { 
          DoSomethingThatUsesSqlWmiManagement_();
   }
   catch
   {   
            handle the missing assembly
   }
}

You probably should catch only the specific Exception.

like image 42
Ðаn Avatar answered Jun 03 '23 06:06

Ðаn