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.
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;
}
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With