Article purpose
Introduced in. Ways to get the number of lines of code in net
Code
[stathread]static void Main (string[] args) { ReportError ("yay!");} static private void ReportError (string Message) { StackFrame callstack = new StackFrame (1, true); Console.Write ("Error:" + Message + ", File:" + callstack.getfilename () + ", line:" + callstack.getfilelinenumber ());}
StackFrame (Int32, Boolean)Initializes a new instance of the StackFrame class corresponding to the frame above the current stack frame, optionally capturing source information.
GetFileName : Gets the file name that contains the code being executed. This information is typically extracted from the debug symbols of the executable file.
GetMethod : Gets the method in which the frame is executed.
Getfilelinenumber: Gets the line number in the file that contains the code being executed. This information is typically extracted from the debug symbols of the executable file.
StackTrace class with Exception (exception)
try{ throw new Exception ();} catch (Exception ex) { //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 (0); Get the line number from the stack frame, var line = frame. Getfilelinenumber ();}
. A new method of NET4.5
static void Somemethodsomewhere () { showmessage ("Boo");} ... static void ShowMessage (String message, [callerlinenumber] int linenumber = 0, [callermembername] String Caller = null) { MessageBox.Show (message + "at line" + linenumber + "(" + Caller + ")");