How to get current line number

         static void Main(string[] args)
        {
            try
            {               
                throw new Exception();
            }
            catch (Exception ex)
            {
                // Get stack trace for the exception with source file information
                var trace = new StackTrace(ex, true);

                // Get the top stack frame
                var frame = trace.GetFrame(0);

                // Get the line number from the stack frame
                var line = frame.GetFileLineNumber();

                var LineNumber = ExceptionHelper.LineNumber(ex);

                System.Diagnostics.StackTrace trace_ = new System.Diagnostics.StackTrace(ex, true);
                var lineNo = trace_.GetFrame(0).GetFileLineNumber();

                var message = ex.Message;
                var HelpLine = ex.HelpLink;
                var Source = ex.Source;
                var StackTrace = ex.StackTrace;
                var MethodName = ex.TargetSite;              

            }

        }

 

     public static class ExceptionHelper
    {
        public static int LineNumber(this Exception e)
        {

            int linenum = 0;
            try
            {
                linenum = Convert.ToInt32(e.StackTrace.Substring(e.StackTrace.LastIndexOf(":line") + 5));
            }
            catch
            {
                //Stack trace is not available!
            }
            return linenum;
        }
    }


-----------------------------------------------------------------------------------------------------
 A trace of the method calls is called a stack trace. The stack trace listing provides a way to follow the call stack to the line number in the method where the exception occurs.

Next PostNewer Post Previous PostOlder Post Home

0 comments:

Post a Comment