通过System.Diagnostics.StackTrace获取代码所在行号和文件信息

        /// <summary>
        /// Get line number of code dynamically
        /// </summary>
        /// <param name="skipFrames">number of frames to skip</param>
        /// <returns>line number of code after skipping frames</returns>
        public static int GetCodeLineNum(int skipFrames)
        {
            StackTrace st = new StackTrace(skipFrames, true);
            StackFrame fram = st.GetFrame(0);
            int lineNum = fram.GetFileLineNumber();
            return lineNum;
        }

skipFrames == 0 :

获取的是 System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(skipFrames, true); 所在行号

skipFrames == 1:

获取的是函数GetCodeLineNum被调用时所在行号


获取文件路径信息

        /// <summary>
        /// Get file name information of code dynamically
        /// </summary>
        /// <param name="skipFrames">number of frames to skip</param>
        /// <returns>file name information of code after skipping frames</returns>
        public static string GetCodeFileName(int skipFrames)
        {
            StackTrace st = new StackTrace(skipFrames, true);
            StackFrame fram = st.GetFrame(0);
            string source = fram.GetFileName();
            return source;
        }

获取Exception中行号

int lineNum = ex.StackTrace.IndexOf("行号");

相关文章:

  • 2021-09-22
  • 2021-06-27
  • 2022-12-23
  • 2021-05-21
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-11-20
  • 2021-07-25
  • 2022-12-23
  • 2022-01-20
  • 2022-01-09
相关资源
相似解决方案