Reputation: 2452
How can I find the full name of a calling method in C#? I have seen solutions:
How I can get the calling methods in C#
How can I find the method that called the current method?
Get Calling function name from Called function
But they only give me the top level. Consider the example:
namespace Sandbox
{
class Program
{
static void Main(string[] args)
{
test();
}
static void test()
{
var stackTrace = new StackTrace();
var methodBase = stackTrace.GetFrame(1).GetMethod();
Console.WriteLine(methodBase.Name);
}
}
}
This simply outputs 'Main'. How can I get it to print 'Sandbox.Program.Main'?
It's for a simple logging framework that I am working on.
Adding onto Matzi's Answer:
Here is the solution:
namespace Sandbox
{
class Program
{
static void Main(string[] args)
{
test();
}
static void test()
{
var stackTrace = new StackTrace();
var methodBase = stackTrace.GetFrame(1).GetMethod();
var Class = methodBase.ReflectedType;
var Namespace = Class.Namespace; // Added finding the namespace
Console.WriteLine(Namespace + "." + Class.Name + "." + methodBase.Name);
}
}
}
It produces 'Sandbox.Program.Main' like it should.
Upvotes: 23
Views: 26066
Reputation: 366
The current calling namespace which is not equal as the current namespace:
var mNamespace = new StackTrace().GetFrames()?.Select(x =>
{
try
{
return x.GetMethod().ReflectedType?.Namespace;
}
catch (Exception)
{
return string.Empty;
}
}).First(x => x != new StackTrace().GetFrame(0).GetMethod().ReflectedType?.Namespace);
Upvotes: 0
Reputation: 1085
I think the best way to get the full name is:
this.GetType().FullName + "." + System.Reflection.MethodBase.GetCurrentMethod().Name;
Or try this:
string method = string.Format("{0}.{1}", MethodBase.GetCurrentMethod().DeclaringType.FullName, MethodBase.GetCurrentMethod().Name);
And if you want to display the most recent function call, you can use:
StackTrace st = new StackTrace();
StackFrame sf = st.GetFrame(0);
var methodName = sf.GetMethod();
But if you want to display the tree of calling functions, you can do it like this:
if (st.FrameCount >1)
{
// Display the highest-level function call
// in the trace.
StackFrame sf = st.GetFrame(st.FrameCount-1);
Console.WriteLine(" Original function call at top of call stack):");
Console.WriteLine(" {0}", sf.GetMethod());
}
For more information.
Upvotes: 4
Reputation: 13450
In the System.Reflection.MethodBase
method GetCurrentMethod
, you can find full information about the call stack using classes, etc.
Upvotes: 0
Reputation: 1495
With this method you can reliably get the full name
public void HandleException(Exception ex, [CallerMemberName] string caller = "")
{
if (ex != null)
{
while (ex.InnerException != null)
ex = ex.InnerException;
foreach (var method in new StackTrace().GetFrames())
{
if (method.GetMethod().Name == caller)
{
caller = $"{method.GetMethod().ReflectedType.Name}.{caller}";
break;
}
}
Console.WriteLine($"Exception: {ex.Message} Caller: {caller}()");
}
}
Upvotes: 3