【发布时间】:2012-06-09 10:03:00
【问题描述】:
如何按类型查找 .cs 文件的路径?
函数原型:
string FindPath(Type);
返回类似 "C:\Projects\.....\MyClass.cs"
【问题讨论】:
-
为什么需要这个?我不确定在运行时是否可行,因为所有代码都被编译成程序集。
-
停止应用程序(调试 + 停止调试)并重建您的项目。
标签: c#
如何按类型查找 .cs 文件的路径?
函数原型:
string FindPath(Type);
返回类似 "C:\Projects\.....\MyClass.cs"
【问题讨论】:
标签: c#
在 .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
【讨论】:
public HomeController() : base(TraceFileLocation()) 行做一些事情。如果您在实例级别上执行此操作,您可能希望将 [CallerFilePath] 的值缓存在静态集合中,以防止在解析路径时做不必要的工作(我希望实际从中获得价值)
这是不可能的,没有这样的关系。一个类可以是部分的,因此它甚至可以来自多个不同的源文件。
【讨论】:
所有类都在程序集(.exe 或 .dll)中编译。我认为您无法获取类的源文件的路径,因为该类甚至可能不存在(如果您已将 .exe 文件复制到另一台机器)。
但您可以获得当前正在运行的程序集(.exe 文件)的路径。看看这个答案:Get the Assembly path C#
string file = (new System.Uri(Assembly.GetExecutingAssembly().CodeBase)).AbsolutePath;
【讨论】:
如果您在 Visual Studio 中查看,我们可以使用“Go to Defenition 或 F12”直接跳转到特定类型的源代码,我相信这是通过使用 Workspace API 实现的,深入挖掘 Workspace API 功能可能会发现一些解决方案.
此处的文档链接:Workspace
【讨论】: