如何在C#中按类型查找.cs文件的路径

如何按类型查找.cs文件的路径?

function原型:

string FindPath(Type);

返回类似“C:\ Projects \ ….. \ MyClass.cs”的内容

在.Net 4.5中,您可以使用CallerFilePathreflection属性(来自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 

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

那是不可能的,没有这种关系。 类可以是部分的,因此它甚至可以来自几个不同的源文件。

所有类都以程序集(.exe或.dll)编译。 我不认为你可以获得类的源文件的路径,因为该类可能甚至不存在(如果您已将.exe文件复制到另一台机器)。

但是您可以获取正在运行的当前程序集(.exe文件)的路径。 看看这个答案: 获取assembly路径C#

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