JJLL
JJLL

Reputation: 394

Best way to debug File IO errors in Visual Studio

In Visual Studio, whenever I have a File IO exception, I can see a global unhandled exception like this:

System.IO.FileNotFoundException: The system cannot find the file specified.

However it doesn't say what file it's attempting to access, or any other information that can help me locate where in the code is calling this file access. I've done quite a bit of online searches and tried looking at the Call Stack, but I can't figure out an easy way to debug this, other than setting break points everywhere and try to step into the exact line where the exception happens.

I'm new to Visual Studio and I'm wondering if people have suggestions on how to debug this better. I'm sure this is a piece of cake to experienced Visual Studio users!

I'm writing in C#/C++ and using Visual Studio 2013 Ultimate.

Update: My mistake, I thought I inherited some global unhandled exception code, but it turned out it's automatic generated code in App.g.i.cs:

#if DEBUG && !DISABLE_XAML_GENERATED_BREAK_ON_UNHANDLED_EXCEPTION
        UnhandledException += (sender, e) =>
        {
            if (global::System.Diagnostics.Debugger.IsAttached) global::System.Diagnostics.Debugger.Break();
        };
#endif

Upvotes: 2

Views: 1954

Answers (2)

jglouie
jglouie

Reputation: 12880

These steps work in VS 2010 -- I'd expect it to be very similar if not identical in newer versions.

While in Visual Studio, go to:

  • Debug > Exceptions menu
  • Expand Common Language Runtime Exceptions
  • Expand System.IO
  • Put a checkmark in the Thrown column for System.IO.FileNotFoundException

Now, run your code in Debug mode.

Studio will alert you when the exception is thrown. Here's a screenshot of what it will look like. In that window, you can click View Details to graphically browse the exception information.

This is great for debugging on your machine - I use it all the time. However, you should have a strategy (e.g. good, configurable logging) in case you need to debug these types of information on someone else's machine.

enter image description here

Upvotes: 3

John Saunders
John Saunders

Reputation: 161773

Simply looking at the stack trace should show you where in the code the exception comes from. That should give you a big hint about which file it might be.

Try displaying ex.ToString() to see the entire stack trace.

Upvotes: 1

Related Questions