Open DTE solution from another program (not add-in)

二次信任 提交于 2019-12-06 02:00:01

Yes you can. You just need to activate an instance using the COM CLSID for Visual Studio. An example is below. It actually creates a solution and adds two projects to it but the same initialization applies when opening an existing solution.

A couple of caveats:

  1. Mind the COM threading model. The code created from the console app template is sufficient:

    [STAThread]
    static void Main()
    
  2. If you have a powerful VS extension like ReSharper installed, you might be better off suspending it if you don't need it for the VS automation. ReSharper had VS commands that control it.

        Console.WriteLine("Opening Visual Studio");
        var dte = (DTE)Activator.CreateInstance(Type.GetTypeFromProgID("VisualStudio.DTE.10.0",true),true);
    
        Console.WriteLine("Suspending Resharper");
        dte.ExecuteCommand("ReSharper_Suspend");
    
        Console.WriteLine("Working with {0}, {1} edition", dte.FullName, dte.Edition);
        dte.SuppressUI = true;
        dte.UserControl = false;
    
        foreach (var solution in mySolutionInfoList)
        {
            try
            {                    
                dte.Solution.Create(solution.directory, solution.name);                    
                dte.Solution.AddFromTemplate(csharpTemplatePath, solution.directory + "ClassLibrary1", "ClassLibrary1");
                dte.Solution.AddFromTemplate(vcTemplatePath, solution.directory + "Win32Dll", "Win32Dll");
                Directory.CreateDirectory(solution.directory); // ensure directory exists. Otherwise, user will be asked for save location, regardless of SupressUI value
                dte.Solution.Close(true); 
                Console.WriteLine();
            }
            catch (Exception e)
            {
                Console.Error.WriteLine(e);
            }
        }
    
        Console.WriteLine("Resuming Resharper");
        dte.ExecuteCommand("ReSharper_Resume");
    
        try
        {
            dte.Quit();
        }
        catch (Exception e)
        {
            Console.Error.WriteLine(e);
        }
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!