9

Suppose I am working on Welcome.cs file. In the constructor I want to print "Welcome". However, If I put the same code in HelloWorld.cs, it should print HellowWorld. How do I do that?

Preet Sangha
  • 64,563
  • 18
  • 145
  • 216
user2039445
  • 253
  • 1
  • 4
  • 17

5 Answers5

14

You can try

string thisFile = new System.Diagnostics.StackTrace(true).GetFrame(0).GetFileName(); 
Schaemelhout
  • 685
  • 9
  • 25
  • 2
    This is the way to do it. Note that the `true` means include debug information. This only works on a debug build, which emits the `pdb` file containing source information. – harpo Apr 30 '13 at 08:30
  • 1
    This is the way to do it if OP hadn't been confused. =) – J. Steen Apr 30 '13 at 08:32
  • @harpo So this wouldn't work in production build? – Andrew Jul 04 '19 at 18:40
11

if I've understood correctly, try this.GetType().Name

NDJ
  • 5,189
  • 1
  • 18
  • 27
11

How to print

[current file name - method name - 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("Test");

Output:

Program.cs_Main(11): Test

illegal-immigrant
  • 8,089
  • 9
  • 51
  • 84
8

Try this to get the file name:

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

To get the current line:

int currentLine = new System.Diagnostics.StackTrace(true).GetFrame(0).GetFileLineNumber(); 
Carlos Landeras
  • 11,025
  • 11
  • 56
  • 82
0

If you want to get the class name, you can use Reflection technique.

eg:

Type classType = yourObject.GetType();

you can get the name of the class from

classType.Name

Arun
  • 3,478
  • 8
  • 33
  • 46