Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using C#, how do I create a new Visual Studio 2012 Solution programmatically?

I followed this Stack Overflow post regarding how to create a project for VS2010, hoping that it would point me in the correct direction, but it doesn't cover creating a VS2012 project or solution.

I also explored using SLNTools, but I don't see how to create a new solution from scratch.

Ultimately, I would like to create 3-4 VS2012 projects programmatically and then add them to a solution which is also created programmatically.


I attempted a solution based on this Stack Overflow post, but I get an odd error. Here is the code:

    Type typeDTE = Type.GetTypeFromProgID("VisualStudio.DTE.11.0");
    var dte = (DTE)Activator.CreateInstance(typeDTE, true);
    var sln = (Solution2)dte.Solution;
    sln.Create(@"D:\Visual Studio\Projects","Test");

And here is the error:

enter image description here

like image 760
Matt Cashatt Avatar asked Jan 02 '14 21:01

Matt Cashatt


2 Answers

This works for me (VS2012 Ultimate):

static void Main(string[] args)
{
    System.Type type = System.Type.GetTypeFromProgID("VisualStudio.DTE.11.0");
    Object obj = System.Activator.CreateInstance(type, true);
    EnvDTE.DTE dte = (EnvDTE.DTE)obj;
    dte.MainWindow.Visible = true; // optional if you want to See VS doing its thing

    // create a new solution
    dte.Solution.Create(@"C:\NewSolution\", "NewSolution");
    var solution = dte.Solution;

    // create a C# WinForms app
    solution.AddFromTemplate(@"C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\ProjectTemplatesCache\CSharp\Windows\1033\WindowsApplication\csWindowsApplication.vstemplate",
        @"C:\NewSolution\WinFormsApp", "WinFormsApp");

    // create a C# class library
    solution.AddFromTemplate(@"C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\ProjectTemplatesCache\CSharp\Windows\1033\ClassLibrary\csClassLibrary.vstemplate",
        @"C:\NewSolution\ClassLibrary", "ClassLibrary");

    // save and quit
    dte.ExecuteCommand("File.SaveAll");
    dte.Quit();
}

[Edit:] Looking under HKCR, it looks like there's a VisualStudio.DTE (without the .11.0) that will point to the latest version of VS. So on my machine with VS2012 and VS2013, it will use the latter.

like image 163
Jimmy Avatar answered Sep 27 '22 18:09

Jimmy


Tested and working using .NET4 Winforms, and a reference to EnvDTE100.dll (which should also add references to EnvDTE90.dll, EnvDTE80.dll, and EnvDTE.dll)

Type type = Type.GetTypeFromProgID("VisualStudio.DTE.11.0");
Object obj = System.Activator.CreateInstance(type, true);
EnvDTE80.DTE2 dte = (EnvDTE80.DTE2)obj;
EnvDTE100.Solution4 _solution = (EnvDTE100.Solution4)dte.Solution;
_solution.Create(@"C:\Test\", "Test");
_solution.SaveAs(@"C:\Test\Test.sln");
like image 36
Xenolightning Avatar answered Sep 27 '22 19:09

Xenolightning