I'm working with a managed exe that crashes immediately when run. Usually I'd expect a dialog which allows an option to launch the debugger but no such luck in this case. Also, the program crashes too quickly for me to use attach to process in VS.
Start it within the debugger (F5 or Ctrl+shift+b). You should be able to set an arbitrary breakpoint (like in the main function) and single setp your way through.
Immediate crash?
I'd use ildasm just to make sure I've got a valid (looking) managed executable.
Also, I've been bitten a few times by having the .exe on a networked drive, and not having the permissions set correctly.
One common reason for this is if an exception is thrown in the constructor of whatever object is creating when calling Application.Run... as in:
Application.Run(new MyForm());
If the MyForm constructor throws an exception, it will usually just crash.
Also consider using Assembly Binding Log Viewer to determine if you are missing a required assembly, or have a versioning issue.
If you have WinDBG installed, use File > Open Executable to open the application directly under the debugger and automatically break immediately.
You can then use the commands under Debug (i.e., Go) to execute it normally and debug it. Also load the SOS Extensions. Not as nice as Visual Studio, but useful if you only have the EXE (and hopefully the PDB, although that's optional) and no source.
Example: This is my source code, which we assume is unavailable:
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
int x = 10 - 10;
int i = 2000/x;
Application.Run(new Form1());
}
This crashes immedately, with no chance for you to attach a debugger in time. This is the WinDBG output after hitting "Run":
After loading SOS.dll, you can use !DumpStack to see where the Exception was thrown:
Note that JIT or compiler optimizations may cause methods to be inlined which may make the StackTrace not 100% reliable, but for a quick overview it works.
WinDBG is a bit arcane, but once you got some basics done it's awesome and at least helps finding the root of the issue.
One additional option not mentioned above is to insert a
Debugger.Break
statement at the very beginning of the program - perhaps wrapped in a #ifdef DEBUG to make it easier to skip over when its time to build for release. I've used this technique to debug Windows services that were crashing early on.