C# 动态获取代码所在行号

通过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("行号");

相关文章