c# - 以编程方式从插件获取当前的 Visual Studio IDE 解决方案目录

标签 c# visual-studio solution envdte vs-extensibility

我有一些工具可以对 .NET 解决方案执行更新,但它们需要知道解决方案所在的目录。

我将这些工具添加为外部工具,它们出现在 IDE 工具菜单中,并提供 $(SolutionDir) 作为参数。这很好用。

但是,我希望用户可以通过自定义顶级菜单(我为此创建了一个 Visual Studio 集成包项目)和解决方案节点上的上下文菜单(我为此创建了一个 Visual Studio 集成包项目)在 IDE 中更轻松地访问这些工具创建了一个 Visual Studio 插件项目)。我正在寻找一种通过这些上下文获取当前解决方案目录的方法。

我尝试从 VisualStudio.DTE 对象获取解决方案信息:

EnvDTE.DTE dte = (EnvDTE.DTE)System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE");
string solutionDir = System.IO.Path.GetDirectoryName(dte.Solution.FullName);

但是,这会返回加载项的解决方案目录,而不是当前解决方案。

我尝试回显 $(SolutionDir) 并读回:

System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "echo $(SolutionDir)");

// The following commands are needed to redirect the standard output.
// This means that it will be redirected to the Process.StandardOutput StreamReader.
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
// Do not create the black window.
procStartInfo.CreateNoWindow = true;
// Now we create a process, assign its ProcessStartInfo and start it
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
// Get the output into a string
string result = proc.StandardOutput.ReadToEnd();

但是,这返回了 IDE 的目录,而不是当前的解决方案。

我在解决方案节点 CommandBar 中没有看到任何相关信息。

或者,如果有一种方法可以以编程方式访问定义的 Visual Studio 外部工具并启动它们(使用已经定义的宏参数),那也行得通。

解决方案是什么?

最佳答案

EnvDTE.DTE dte = (EnvDTE.DTE)System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE"); string solutionDir = System.IO.Path.GetDirectoryName(dte.Solution.FullName);

But, this returns the solution directory for the add ins, not the current solution.

您获取目录的方法很好。问题在于您获取 VisualStudio.DTE 对象的方式。这段代码在哪里调用?我假设它在您的加载项中。您是否在 Visual Studio 中执行(调试)加载项,这会打开您打开解决方案的另一个 Visual Studio 实例?所以你有两个 Visual Studio 实例。

GetActiveObject("VisualStudio.DTE") 获取一个随机的 Visual Studio 实例。在您的情况下,显然是带有加载项项目的 Visual Studio,因为您获得了加载项的路径。这是为了解释您的问题的原因。

获取DTE的正确方法非常简单。事实上,您的加载项已经引用了它在其中运行(即打开解决方案)的 DTE。它存储在您的加载项连接类中的全局变量 _applicationObject 中。它是在您的加载项在 OnConnection 事件处理程序中启动时设置的。所以你只需要调用:

string solutionDir = System.IO.Path.GetDirectoryName(_applicationObject.Solution.FullName);

关于c# - 以编程方式从插件获取当前的 Visual Studio IDE 解决方案目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2054182/

相关文章:

visual-studio-2010 - 文件更改后 msbuild.exe 不会提供新输出

c# - c# 解决方案中的命名空间和文件夹结构 : how should folders on disk be organised?

c# - java lucene中lucene.net索引目录的使用

c# - 解析具有多个值行的文件 C#

c# - 使用 global::keyword 的现有编码方法的性能问题

c++ - 为什么 Visual Studio 2013 会发出 C4996 错误?

c# - 运行时调试不起作用。

C# -> 检测浏览器宽度

c# - 如何使两个类属性引用相同的值

c++ - 是否可以从 .sln 文件读取/检索 C++ 源代码?