code_junkie

How can I find the method that called the current method?

Nov 11th, 2011
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.67 KB | None | 0 0
  1. using System.Diagnostics;
  2. // get call stack
  3. StackTrace stackTrace = new StackTrace();
  4.  
  5. // get calling method name
  6. Console.WriteLine(stackTrace.GetFrame(1).GetMethod().Name);
  7.  
  8. new StackFrame(1).GetMethod().Name;
  9.  
  10. /// <summary>
  11. /// Returns the call that occurred just before the "GetCallingMethod".
  12. /// </summary>
  13. public static string GetCallingMethod()
  14. {
  15. return GetCallingMethod("GetCallingMethod");
  16. }
  17.  
  18. /// <summary>
  19. /// Returns the call that occurred just before the the method specified.
  20. /// </summary>
  21. /// <param name="MethodAfter">The named method to see what happened just before it was called. (case sensitive)</param>
  22. /// <returns>The method name.</returns>
  23. public static string GetCallingMethod(string MethodAfter)
  24. {
  25. string str = "";
  26. try
  27. {
  28. StackTrace st = new StackTrace();
  29. StackFrame[] frames = st.GetFrames();
  30. for (int i = 0; i < st.FrameCount - 1; i++)
  31. {
  32. if (frames[i].GetMethod().Name.Equals(MethodAfter))
  33. {
  34. if (!frames[i + 1].GetMethod().Name.Equals(MethodAfter)) // ignores overloaded methods.
  35. {
  36. str = frames[i + 1].GetMethod().ReflectedType.FullName + "." + frames[i + 1].GetMethod().Name;
  37. break;
  38. }
  39. }
  40. }
  41. }
  42. catch (Exception) { ; }
  43. return str;
  44. }
  45.  
  46. StackFrame frame = new StackFrame(1);
  47. frame.GetMethod().Name; //Gets the current method name
  48.  
  49. MethodBase method = frame.GetMethod();
  50. method.DeclaringType.Name //Gets the current class name
  51.  
  52. private static MethodBase GetCallingMethod()
  53. {
  54. return new StackFrame(2, false).GetMethod();
  55. }
  56.  
  57. private static Type GetCallingType()
  58. {
  59. return new StackFrame(2, false).GetMethod().DeclaringType;
  60. }
Add Comment
Please, Sign In to add comment