如何按类型查找.cs文件的路径?
功能原型:
string FindPath(Type);
返回类似“C:\ Projects \ ..... \ MyClass.cs”
的内容答案 0 :(得分:17)
在.Net 4.5中,您可以使用CallerFilePath
反射属性(来自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
答案 1 :(得分:6)
这是不可能的,没有这样的关系。一个类可以是部分的,所以它甚至可以来自几个不同的源文件。
答案 2 :(得分:2)
所有类都以程序集(.exe或.dll)编译。我认为你不能获得类的源文件的路径,因为该类可能甚至不存在(如果你已经将.exe文件复制到另一台机器上)。
但是你可以获得正在运行的当前程序集(.exe文件)的路径。看看这个答案:Get the Assembly path C#
string file = (new System.Uri(Assembly.GetExecutingAssembly().CodeBase)).AbsolutePath;
答案 3 :(得分:0)
如果您在Visual Studio中查看,我们可以使用“转到定义或F12”直接跳至特定类型的源代码,我相信这是通过使用Workspace API实现的,深入研究Workspace API功能可能会揭示一些解决方案
此处的文档链接:Workspace