将VS 2005解决方案文件(.sln)打开到内存中

我想在内存中打开一个现有的.sln文件。

非工作方法的示例:

private Solution2 OpenSolution(string filePath) { Solution2 sln; sln.Open(filePath); return sln; } 

如果我有一个Solution2的实例,那么我可以调用方法Open; 但是我如何获得Solution2的实例

我的目标是获得足够的项目并阅读其中的一些设置……但这很容易获得解决方案。

先谢谢,路易斯

您可以以编程方式创建隐藏的Visual Studio实例,然后使用它来操作您的解决方案。 此示例将列出生活在给定解决方案中的所有项目。

 using System; using System.Runtime.InteropServices; using EnvDTE; using EnvDTE80; namespace so_sln { class Program { [STAThread] static void Main(string[] args) { System.Type t = System.Type.GetTypeFromProgID("VisualStudio.DTE.8.0", true); DTE2 dte = (EnvDTE80.DTE2)System.Activator.CreateInstance(t, true); // See http://msdn.microsoft.com/en-us/library/ms228772.aspx for the // code for MessageFilter - just paste it into the so_sln namespace. MessageFilter.Register(); dte.Solution.Open(@"C:\path\to\my.sln"); foreach (Project project in dte.Solution.Projects) { Console.WriteLine(project.Name); } dte.Quit(); } } public class MessageFilter : IOleMessageFilter { ... Continues at http://msdn.microsoft.com/en-us/library/ms228772.aspx 

(STAThread和MessageFilter的无意义是“由于外部multithreading应用程序和Visual Studio之间的线程争用问题”,无论这意味着什么。粘贴在http://msdn.microsoft.com/en-us/library/的代码中ms228772.aspx使它工作。)

Solution2是一个接口,而不是一个类。 您不能直接创建Solution2类型的对象,只能将对象引用为包含Solution2接口的Solution2。

据我所知,实现Solution2接口的类只能作为Visual Studio集成中接口集合的一部分使用,因此您必须执行与RichieHindle所提到的类似的操作,并创建一个新的隐藏Visual Studio实例加载解决方案。

如果你只是想从sln文件中获取一些设置,我可能会建议你自己解析它,文件格式非常简单。 如果你试图提取一个设置,很可能是奇怪的边缘情况,如果Visual Studio为你解析sln,解析你自己的sln也行不通也无法解决你想要做的事情。

我对此没有多少经验,但试试这篇 msdn文章。 它不是您正在寻找的,但它们确实在示例代码中实例化了一个solution2对象。

Solution2等基本上是Visual Studio SDK的一部分,您必须使用您的应用程序重新分发(具有所有许可含义)。

由于.sln文件是普通的旧XML,因此您始终可以在XmlDocument打开它,然后在其中打开XPath。