Wednesday, April 16, 2008

Get calling function name from the called function in C#

I was looking to retrieve the function name from where a desired
function is called so that I can use it for logging purpose. I found
that it could be obtained using StackFrame object which contains the
entire hierarchy of the function stack.

private StackFrame GetCallingStackFrame()
{
// determine the method that called the one that is calling this one.
// this is not just two up the stack because of rich exception support.
StackFrame sf = null;

// start at 2. 1 for this one and another for the one above that.
StackTrace st = new StackTrace(2, true);
Type thisType = GetType();
foreach (StackFrame sfi in st.GetFrames())
{
// find a calling method that is not part of this log class but is part of the same namespace
Type callType = sfi.GetMethod().DeclaringType;
if (callType != thisType && callType.Namespace == thisType.Namespace && !callType.IsInterface)
{ sf = sfi; break; }
}
return sf;
}

This can then be used like so.

StackFrame sf = GetCallingStackFrame();
if (sf != null) // if found add info to log message
{
System.Reflection.MethodBase mb = sf.GetMethod();
string methodName = mb != null ? mb.Name : string.Empty;
string fileName = sf.GetFileName();

if (fileName != null)
fileName = fileName.Substring(fileName.LastIndexOf('\\') + 1);
int lineNumber = sf.GetFileLineNumber();

if (fileName != null)
strMsg = fileName + " (" + lineNumber + ") - " + methodName + "
- " + strMsg;
else
strMsg = "unknown - " + methodName + " - " + strMsg;
}