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 :spa

獲取的是 System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(skipFrames, true); 所在行號code

skipFrames == 1:orm

獲取的是函數GetCodeLineNum被調用時所在行號blog


獲取文件路徑信息

        /// <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("行號");
相關文章
相關標籤/搜索