views:

219

answers:

2

I have a command line winforms executable that calls into a Windows winforms application.

Occassionally Ops forget to include the windows exe with the command line exe when deploying the application, leading to an error.

How do I gracefully handle that and show a nice error instead of:

Unhandled Exception: System.IO.FileNotFoundException: Could not load file or ass embly 'MyappFoo, Version=5.1.4303.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified. File name: 'MyAppFoo, Version=5.1.4303.0, Culture=neutral, PublicKeyToken=null' at AppFoo.Program.Main(String[] args)

WRN: Assembly binding logging is turned OFF. To enable assembly bind failure logging, set the registry value [HKLM\Software\M icrosoft\Fusion!EnableLog] (DWORD) to 1. Note: There is some performance penalty associated with assembly bind failure lo gging. To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fus ion!EnableLog].

Edit:

To clarify a bit, how do I intercept the FileNotFoundExcception, when

static int Main(string[] args)
{
   try
   {
      Console.WriteLine"MyPhooApp Command Line (c) PhooSoft 2008");
   }
   catch (System.IO.FileNotFoundException fe)
   {
      Console.WriteLine("Unable to find foo.exe");
      return -1;
   }
}

doesnt writeln either.

+4  A: 

You can use the Reflection-Only loading capability introduced in .NET 2.0. This allows you to load an assembly for inspection without actually loading it into the appdomain.

Assembly.ReflectionOnlyLoad

Assembly.ReflectionOnlyLoadFrom

Josh Einstein
It's worth noting that these functions will still throw a FileNotFound exception if the assembly is not found, but you have the upside of knowing exactly when it may happen.
Fredrik Mörk
True, but the other advantage is that if you try that with the normal assembly load API's the app will never try to probe for the assembly again.The other advantage is that you can use ReflectionOnlyLoadFrom with a file path without screwing up the binding context. If you use Assembly.LoadFrom with a file path, you can wind up loading the same assembly twice.
Josh Einstein
Err... trying to load the same assembly twice. I think fusion fails if it tries to resolve an assembly that was loaded in the loadfrom context.
Josh Einstein
A: 

Could you not simply look for the file with FileInfo.Exists?

Colin Desmond
No, the exception gets thrown before the Main method gets called.
WOPR