How can I get filename of current working cs file

2020-05-28 10:34发布

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?

标签: c#
5条回答
来,给爷笑一个
2楼-- · 2020-05-28 10:40

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

查看更多
我只想做你的唯一
3楼-- · 2020-05-28 10:44

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

查看更多
对你真心纯属浪费
4楼-- · 2020-05-28 10:48

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

查看更多
\"骚年 ilove
5楼-- · 2020-05-28 10:49

You can try

string thisFile = new System.Diagnostics.StackTrace(true).GetFrame(0).GetFileName(); 
查看更多
家丑人穷心不美
6楼-- · 2020-05-28 10:56

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(); 
查看更多
登录 后发表回答