Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get filename of current working cs file and the name of the current class [duplicate]

Tags:

c#

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?

like image 613
user2039445 Avatar asked Apr 30 '13 08:04

user2039445


People also ask

How do I get the filename from the file path?

To extract filename from the file, we use “GetFileName()” method of “Path” class. This method is used to get the file name and extension of the specified path string. The returned value is null if the file path is null.

How does file copy work in c#?

Copy(String, String) is an inbuilt File class method that is used to copy the content of the existing source file content to another destination file which is created by this function. Syntax: public static void Copy (string sourceFileName, string destFileName);


2 Answers

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

like image 114
NDJ Avatar answered Nov 15 '22 04:11

NDJ


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

like image 39
illegal-immigrant Avatar answered Nov 15 '22 02:11

illegal-immigrant