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?
Asked
Active
Viewed 1.8k times
9
-
Code files have no influence on your compiled application. You can have an application with 10.000 classes in one codefile. – Carsten Apr 30 '13 at 08:28
-
4Do you want the name of the **file** or the **class**? They are fundamentally different and anything they have in common is only by convention. – J. Steen Apr 30 '13 at 08:29
-
@J.Steen: Actually the class name. – user2039445 Apr 30 '13 at 08:31
-
@TimSchmelter there are Framework methods for doing this now, so I think it's ok to keep this question – illegal-immigrant Apr 30 '13 at 08:43
5 Answers
14
You can try
string thisFile = new System.Diagnostics.StackTrace(true).GetFrame(0).GetFileName();

Schaemelhout
- 685
- 9
- 25
-
2This 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
-
11
if I've understood correctly, try this.GetType().Name

NDJ
- 5,189
- 1
- 18
- 27
-
1One of us hasn't understood correctly. The OP asked how to get the source file name. – harpo Apr 30 '13 at 08:29
-
-
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