在捕获块中,如何获得抛出异常的行号?
当前回答
更新到答案
// Get stack trace for the exception with source file information
var st = new StackTrace(ex, true);
// Get the top stack frame
var frame = st.GetFrame(st.FrameCount-1);
// Get the line number from the stack frame
var line = frame.GetFileLineNumber();
其他回答
看看这个
StackTrace st = new StackTrace(ex, true);
//Get the first stack frame
StackFrame frame = st.GetFrame(0);
//Get the file name
string fileName = frame.GetFileName();
//Get the method name
string methodName = frame.GetMethod().Name;
//Get the line number from the stack frame
int line = frame.GetFileLineNumber();
//Get the column number
int col = frame.GetFileColumnNumber();
我尝试使用@davy-c的解决方案,但有一个异常“系统。输入字符串的格式不正确。’”,这是由于仍然有文本超过行号,我修改了他发布的代码,并提出:
int line = Convert.ToInt32(objErr.ToString().Substring(objErr.ToString().IndexOf("line")).Substring(0, objErr.ToString().Substring(objErr.ToString().IndexOf("line")).ToString().IndexOf("\r\n")).Replace("line ", ""));
这适用于我在VS2017 c#。
您可以包含与程序集关联的. pdb符号文件,其中包含元数据信息,当抛出异常时,它将在异常起源的堆栈跟踪中包含完整的信息。它将包含堆栈中每个方法的行号。
如果你的堆栈跟踪大于1,它应该是:
var st = new StackTrace(es, true);
// Get the top stack frame
var frame = st.GetFrame(st.FrameCount - 1);
//从栈帧中获取行号 var line = frame.GetFileLineNumber();
简单的方法,使用exception . tostring()函数,它将返回异常描述之后的行。
您还可以检查程序调试数据库,因为它包含关于整个应用程序的调试信息/日志。
推荐文章
- 我如何让红宝石打印一个完整的回溯而不是截断一个?
- Visual Studio:如何打破处理异常?
- 返回文件在ASP。Net Core Web API
- 自定义HttpClient请求头
- 如果我使用OWIN Startup.cs类并将所有配置移动到那里,我是否需要一个Global.asax.cs文件?
- VS2013外部构建错误"error MSB4019: The imported project <path> was not found"
- 从另一个列表id中排序一个列表
- 等待一个无效的异步方法
- 无法加载文件或程序集…参数不正确
- c#中枚举中的方法
- 如何从字符串中删除新的行字符?
- 如何设置一个默认值与Html.TextBoxFor?
- 检查属性是否有属性
- 格式化XML字符串以打印友好的XML字符串
- 返回内容与IHttpActionResult非ok响应