I would like to open into memory an existing .sln file.
Example of a non-working method:
private Solution2 OpenSolution(string filePath)
{
Solution2 sln;
sln.Open(filePath);
return sln;
}
If I have an instance of Solution2 then i can call the method Open; but how can i get an instance of Solution2?
My goal is then to get the adequate project and read some of its settings... but that's easy having access to the solution.
You can programmatically create a hidden instance of Visual Studio, and then use it to manipulate your solution. This example will list out all the projects that live in the given solution.
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
(The nonsense with STAThread and MessageFilter is "due to threading contention issues between external multi-threaded applications and Visual Studio", whatever that means. Pasting in the code from http://msdn.microsoft.com/en-us/library/ms228772.aspx makes it work.)