user2322507
user2322507

Reputation: 141

How to get the LineNumber and Method name inside Exception

So i have a function which in turns call a method that take Exception object as the parameter.

public DataSet SomeFunction()
{    
    try
    {

    }
    catch (Exception ex)
    {
            ErrorLogInDB.LogError(ex);
            throw;
    }
}

public static void LogError(Exception exception)
{
    StackTrace st = new StackTrace(exception, true);
    StackFrame frame = new StackFrame(0);

    MethodBase site = exception.TargetSite;

    string fileName = frame.GetFileName();
    string methodName = site.Name;
    int lineNo = frame.GetFileLineNumber();
    string errorDescription = exception.Message;
}   

From the above function LogError i am getting filename as null, methodname is incorrect and also the line number. How to solve it?

Upvotes: 1

Views: 2076

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460108

Try...

StackTrace trace = new StackTrace(exception, true);
StackFrame stackFrame = trace.GetFrame(trace.FrameCount - 1);
string fileName = stackFrame.GetFileName();
string methodName = stackFrame.GetMethod().Name();
int lineNo = stackFrame.GetFileLineNumber();

Upvotes: 4

Related Questions