Print the source filename and linenumber in C#

Is there any way to retrieve the current source filename and linenumber in C# code and print that value in the console output? Like LINE and FILE in C?

Please advise.

Many thanks


Solution 1:

Anders Hejlsberg presented new API for that in BUILD keynote:

Print current file name, method name and line number

private static void Log(string text,
                        [CallerFilePath] string file = "",
                        [CallerMemberName] string member = "",
                        [CallerLineNumber] int line = 0)
{
    Console.WriteLine("{0}_{1}({2}): {3}", Path.GetFileName(file), member, line, text);
}

Test:

Log(".NET rocks!");

Output:

Program.cs_Main(11): .NET rocks!

What's going on here?

You define a method with optional parameters and decorate them with special attributes. If you call method without passing actual arguments (leave defaults) - the Framework populates them for you.

Solution 2:

This answer is outdated! See @taras' answer for more recent information.


No constant :(

What you can do is a lot uglier :

string currentFile = new System.Diagnostics.StackTrace(true).GetFrame(0).GetFileName(); 
int currentLine = new System.Diagnostics.StackTrace(true).GetFrame(0).GetFileLineNumber(); 

Works only when PDB files are available.

Solution 3:

You can use the StackTrace object from the System.Diagnostics namespace but the information will only be available if the PDB files are there.

PDB files are generated by default for both the Debug and Release builds the only difference is that Debug is setup to generate a full debug info where as the Release build is setup to only generate a pdb (full/pdb-only).

Console.WriteLine(new StackTrace(true).GetFrame(0).GetFileName());

Console.WriteLine(new StackTrace(true).GetFrame(0).GetFileLineNumber());