Click here to Skip to main content
15,867,835 members
Please Sign up or sign in to vote.
5.00/5 (3 votes)
See more:
When creating a process log, I need to know when the log is written, so I need the name of the calling method, and of course, the name of the class who owns that method. The name of the method is done using reflection, but there is no way to get the class name where the method is stored.

This is the sample code :
C#
using System.Windows.Forms;
using System.Reflection;
using System.Diagnostics;

class LogCaller {
    public static void callLogProcess() {
        viewLog("Any log");
    }
    public static void viewLog(string logStatus) {
        StackTrace st = new StackTrace();
        string str;
        str = "Frame Count : " + st.FrameCount.ToString() + "\n";
        int i = 0;
        foreach (StackFrame sf in st.GetFrames()) {
            MethodBase mb = sf.GetMethod();
            str += i.ToString() + "." + mb.Name + " in " + mb.Module.Name + "\n";
            i++;
        }
        MessageBox.Show(str);
    }
}


Then I call the LogCaller.callLogProcess() in a click event of a button, and this is the result :

Frame Count : 25
0.viewLog in Ai.Trade.exe
1.callLogProcess in Ai.Trade.exe
2.button1_Click in Ai.Trade.exe
3.OnClick in System.Windows.Forms.dll
4.OnClick in System.Windows.Forms.dll
5.OnMouseUp in System.Windows.Forms.dll
6.WmMouseUp in System.Windows.Forms.dll
7.WndProc in System.Windows.Forms.dll
8.WndProc in System.Windows.Forms.dll
9.WndProc in System.Windows.Forms.dll
10.OnMessage in System.Windows.Forms.dll
11.WndProc in System.Windows.Forms.dll
12.DebuggableCallback in System.Windows.Forms.dll
13.DispatchMessageW in System.Windows.Forms.dll
14.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop in System.Windows.Forms.dll
15.RunMessageLoopInner in System.Windows.Forms.dll
16.RunMessageLoop in System.Windows.Forms.dll
17.Run in System.Windows.Forms.dll
18.Main in Ai.Trade.exe
19._nExecuteAssembly in mscorlib.dll
20.ExecuteAssembly in mscorlib.dll
21.RunUsersAssembly in Microsoft.VisualStudio.HostingProcess.Utilities.dll
22.ThreadStart_Context in mscorlib.dll
23.Run in mscorlib.dll
24.ThreadStart in mscorlib.dll

How to get the class name who owns the "callLogProcess" method (LogCaller in this case), can anyone help me ?
Posted

1 solution

Hi,
you can try using the below code:

C#
StackFrame frame = new StackFrame(1);
//class name
string className = frame.GetMethod().DeclaringType.Name;
//method name
string methodName = frame.GetMethod().Name;


Regards
 
Share this answer
 
Comments
red_moon 13-Oct-11 6:12am    
Thx a lot, its work. :)
Pravin Patil, Mumbai 13-Oct-11 6:12am    
Very good answer...
Ciumac Sergiu 13-Oct-11 6:31am    
Thx!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900