Blog - Single Post

Create a Visual Studio Solution file dynamically

  • Thursday, February 12, 2015
  • by

This code snipped will help a scenario when you have a bunch of C# projects that you want to add to a single solution file. You can add each project to your solution manually, but that will be tedious.

The below code snippet will scan all C# project files in the recursive directories and add those to a solution file. This will save a lot of time.

//solutionName = "mySol.sln"; give a solution name with extension

//readDirectory = @"c:\source\Allprojects"; give the direct where it has to loop through the projects

public void CreateSolutionFile(string solutionName, string readDirectory)
        {
            using (var writer = new StreamWriter(solutionName, false, Encoding.UTF8))
            {
                writer.WriteLine("Microsoft Visual Studio Solution File, Format Version 12.00");
                writer.WriteLine("# Visual Studio 2013");
                writer.WriteLine("VisualStudioVersion = 12.0.31101.0");
                writer.WriteLine("MinimumVisualStudioVersion = 10.0.40219.1");

                var seenElements = new HashSet<string>();
                foreach (var file in (new DirectoryInfo(readDirectory)).GetFiles("*.csproj", SearchOption.AllDirectories))
                {
                    string fileName = Path.GetFileNameWithoutExtension(file.Name);
                    if (seenElements.Add(fileName))
                    {
                        var guid = ReadGuid(file.FullName);
                        writer.WriteLine(
                            string.Format(@"Project(""0"") = ""{0}"", ""{1}"",""{2}""", 
                            fileName, 
                            file.FullName.Replace(readDirectory,string.Empty), 
                            "{"+guid+"}"));
                        writer.WriteLine("EndProject");
                    }
                }
            }
        }

static Guid ReadGuid(string filePath)
        {
            using (var file = File.OpenRead(filePath))
            {
                XElement elements = XElement.Load(XmlReader.Create(file));
                return Guid.Parse(elements.Descendants().First(element => element.Name.LocalName == "ProjectGuid").Value);
            }
        }