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

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

Function Prototype:

string FindPath(Type);

It returns something like "C: \ Projects \ ..... \ MyClass.cs"

+5
source share
3 answers

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

+12
source

It is impossible, there is no such attitude. A class can be partial, so it can even come from several source files.

+6
source

All classes are assembled in assemblies (.exe or .dll). I do not think that you can get the path to the source file of the class, because this class may not even exist (if you copied the .exe file to another computer).

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

string file = (new System.Uri(Assembly.GetExecutingAssembly().CodeBase)).AbsolutePath;
+2
source

All Articles