How to find path to .cs file by its type in C#

后端 未结 4 843
耶瑟儿~
耶瑟儿~ 2020-12-03 15:39

How to find path to .cs file by its type?

Prototype of function:

string FindPath(Type);

Returns something like \"C:\\Projects\\.....\\M

4条回答
  •  佛祖请我去吃肉
    2020-12-03 16:22

    In .Net 4.5 you can use the CallerFilePath reflection attribute (from MSDN):

    // using System.Runtime.CompilerServices 
    // using System.Diagnostics; 
    
    public void DoProcessing()
    {
        TraceMessage("Something happened.");
    }
    
    public void TraceMessage(string message,
            [CallerMemberName] string memberName = "",
            [CallerFilePath] string sourceFilePath = "",
            [CallerLineNumber] int sourceLineNumber = 0)
    {
        Trace.WriteLine("message: " + message);
        Trace.WriteLine("member name: " + memberName);
        Trace.WriteLine("source file path: " + sourceFilePath);
        Trace.WriteLine("source line number: " + sourceLineNumber);
    }
    
    // Sample Output: 
    //  message: Something happened. 
    //  member name: DoProcessing 
    //  source file path: c:\Users\username\Documents\Visual Studio 2012\Projects\CallerInfoCS\CallerInfoCS\Form1.cs 
    //  source line number: 31
    

    See: http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.callerfilepathattribute(v=vs.110).aspx

提交回复
热议问题