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
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}()");
}
}
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 info
in System.Reflection.MethodBase
method GetCurrentMethod
you can find full information about callstack using classes etc
This is something like here.
MethodBase method = stackTrace.GetFrame(1).GetMethod();
string methodName = method.Name;
string className = method.ReflectedType.Name;
Console.WriteLine(className + "." + methodName);
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);