Method in.NET to get the number of lines of code

  • 2020-12-20 03:32:24
  • OfStack

Purpose of the article

Describes how to get 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 the source information.

GetFileName: Gets the file name containing the code being executed. This information is usually extracted from the debug symbol of the executable.

GetMethod: Gets the method in which the frame is executed.

GetFileLineNumber: Gets the line number of the code executed in the file. This information is usually extracted from the debug symbol of the executable.

StackTrace class using 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(); 
} 

New method. 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 + ")"); 
} 

Related articles: