Andy
Andy

Reputation: 2762

.NET Exception handler page: How to show line number with exception?

How to identify the line nr. where the exception has occured and show a piece of code around the exception?

I would like to implement a custom exception handler page which would display the stack trace, and I'm looking for the easiest way to accomplish the above. While most of the information is available through the Exception object, the source code information is not available there.

Upvotes: 0

Views: 1344

Answers (1)

SLaks
SLaks

Reputation: 887433

You need to use the StackTrace class.

For example:

var st = new StackTrace(exception, true);

var sourceFrame = Enumerable.Range(0, st.FrameCount).FirstOrDefault(i => st.GetFrame(i).GetFileLineNumber() > 0);

This code will find the first frame which has line number information available, or null, if none of the frames have line numbers.

You can then call the methods of the StackFrame object to get more information. Note that source information is usually only available in debug builds.

Upvotes: 1

Related Questions