This is part of something I used in a logging component in a similar situation, although I believe it requires the
pdb
file to be present. It doesn't trace back the exception like you're doing, but it is a nice way to instrument the code.
public static void DebugWriteTrace()
{
System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(true);
string f1info, f2info;
GetTraceInfo(trace, out f1info, out f2info);
Write(0, f1info + f2info);
}
private static void GetTraceInfo(StackTrace trace, out string f1, out string f2)
{
System.Diagnostics.StackFrame sf = trace.GetFrame(1);
int lineNo = sf.GetFileLineNumber();
f1 = System.IO.Path.GetFileNameWithoutExtension(sf.GetFileName())
+ ":" + sf.GetMethod().Name
+ ((lineNo != 0) ? ", Ln " + lineNo.ToString() : "");
f2 = string.Empty;
if (trace.FrameCount > 2)
{
sf = trace.GetFrame(2);
lineNo = sf.GetFileLineNumber();
f2 = "; called from " + sf.GetMethod().Name
+ ((lineNo != 0) ? ", Ln " + lineNo.ToString() : "");
}
}
There were overloads for the
DebugWriteTrace
, which is why
GetTraceInfo
is separate and returns two strings instead of one.