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

后端 未结 4 826
耶瑟儿~
耶瑟儿~ 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:13

    That's not possible, there is no such relation. A class can be partial, so it can even come from several different source files.

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-03 16:23

    All classes get compiled in assemblies (.exe or .dll). I don't think you can get the path to the source file of a class, because that class might not even exist (if you have copied the .exe file to another machine).

    But you can get the path to the current assembly (.exe file) that is running. Check out this answer: Get the Assembly path C#

    string file = (new System.Uri(Assembly.GetExecutingAssembly().CodeBase)).AbsolutePath;
    
    0 讨论(0)
  • 2020-12-03 16:32

    If you look within Visual studio, we can directly jump to the source code of a specific type using "Go to Defenition or F12" I believe this is achieved by using Workspace API, digging more into Workspace API functionality may reveal some solution.

    Documentation link here: Workspace

    0 讨论(0)
提交回复
热议问题