原文地址: https://blog.csdn.net/config_man/article/details/24189091
/// <summary>
/// 取得当前源码的哪一行
/// </summary>
/// <returns></returns>
public static int GetLineNum()
{
System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(1, true);
return st.GetFrame(0).GetFileLineNumber();
}
/// <summary>
/// 取当前源码的源文件名
/// </summary>
/// <returns></returns>
public static string GetCurSourceFileName()
{
System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(1, true);
return st.GetFrame(0).GetFileName();
}
/// <summary>
/// 当前代码来自
/// 哪个文件,第几行
/// </summary>
/// <param name="str">自定义内容</param>
/// <param name="fullDir">true路径+文件名;false仅文件名</param>
/// <returns>当前代码来自 哪个文件,第几行</returns>
public static string GetCodeFileNameAndtLineNum(string str = "", bool fullDir = false)
{
System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(1, true);
string FileName = st.GetFrame(0).GetFileName();
try
{
if (fullDir == false)//仅仅需要文件名,而不要完整路径
{
string[] temp = st.GetFrame(0).GetFileName().Split('\\');//分割路径为数组
if (temp.Length > 0)
{
FileName = temp[temp.Length - 1];//取出数组最后一个,即:文件名
}
}
}
catch { FileName = st.GetFrame(0).GetFileName(); }
int LineNum = st.GetFrame(0).GetFileLineNumber();
return $"{str}{FileName},第{LineNum}行";
}
调用:
Console.WriteLine($"心跳[{buffStr}]{send.RemoteEndPoint.ToString()},第{GetLineNum()}行...");
效果: