Tuesday, November 1, 2016

VSIX: Get list of projects in a Visual Studio solution


var solution = VsixHelper.Ide.Solution;
var projects = solution.GetProjects();

foreach (var project in projects)
{
    System.Diagnostics.Debug.WriteLine(project.Name);
}


namespace Vurdalakov
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using EnvDTE80;
    using EnvDTE;
    using Microsoft.VisualStudio.Shell;

    public static class VsixHelper
    {
        public static DTE2 Ide { get; private set; }

        static VsixHelper()
        {
            VsixHelper.Ide = Package.GetGlobalService(typeof(DTE)) as DTE2;
        }

        public static Project[] GetProjects(this Solution solution)
        {
            var projects = new List();

            var enumerator = solution.Projects.GetEnumerator();
            while (enumerator.MoveNext())
            {
                var project = enumerator.Current as Project;
                projects.AddRange(project.GetProjects());
            }

            return projects.ToArray();
        }

        private static Project[] GetProjects(this Project project)
        {
            if (null == project)
            {
                return new Project[0];
            }

            var projects = new List();

            if (project.Kind != ProjectKinds.vsProjectKindSolutionFolder)
            {
                projects.Add(project);
            }

            if (project.ProjectItems != null)
            {
                for (var i = 1; i <= project.ProjectItems.Count; i++)
                {
                    var subProject = project.ProjectItems.Item(i).SubProject;
                    projects.AddRange(GetProjects(subProject));
                }
            }

            return projects.ToArray();
        }
    }
}

No comments:

Post a Comment