【C#】】取得發生exception的程式碼位置行號

取得錯誤發生的真正位置

當程式碼發生exception時,往往想知道真正的位置,可以利用ex.StackTrace找到

string line = "";
int lineInd = ex.StackTrace.IndexOf("行");
if (lineInd > -1)
{
    line = ex.StackTrace.Substring(lineInd , ex.StackTrace.Length - lineInd );
    line = line.Replace("行", "");
}

另外 上網有看到這種,這只能顯示目前所在的行號位置,不是真正exception發生的位置

string 目前行號 = new StackTrace(true).GetFrame(0).GetFileLineNumber().ToString();