Jack Ukleja
Jack Ukleja

Reputation: 13511

MSBUILD: How to parse solution file to get project paths

How can I get the list of project files from a solution when using MSBUILD?

For example getting all the .csproj from a .sln.

Upvotes: 1

Views: 1121

Answers (1)

Jack Ukleja
Jack Ukleja

Reputation: 13511

I was previously using MSBuild Community Tasks's GetSolutionProjects for this but unfortunately it has a dependency on .NET 3.5.

To accomplish this using a CodeTask (available since .NET 4) do the following:

  <UsingTask TaskName="GetProjectsFromSolutionCodeTask" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll" >
    <ParameterGroup>
      <Solution ParameterType="System.String" Required="true"/>
      <Output ParameterType="Microsoft.Build.Framework.ITaskItem[]" Output="true"/>
    </ParameterGroup>
    <Task>
      <Reference Include="System.Xml"/>
      <Reference Include="Microsoft.Build"/>
      <Using Namespace="Microsoft.Build.Construction"/>
      <Code Type="Fragment" Language="cs">
        <![CDATA[
        var _solutionFile = SolutionFile.Parse(Solution); 
        Output = _solutionFile.ProjectsInOrder
            .Where(proj => proj.ProjectType == SolutionProjectType.KnownToBeMSBuildFormat)
            .Select(proj => new TaskItem(proj.AbsolutePath))
            .ToArray();
      ]]>
      </Code>
    </Task>
  </UsingTask>

and invoke it like so:

  <!-- Gets the projects composing the specified solution -->
  <Target Name="GetProjectsFromSolution">
    <GetProjectsFromSolutionCodeTask Solution="%(Solution.Fullpath)">
      <Output ItemName="ProjectFiles" TaskParameter="Output"/>
    </GetProjectsFromSolutionCodeTask >
  </Target>

This will populate a ProjectFiles item collection with the absolute path of all the projects within the solution.

Please note: path to CodeTaskFactory varies by MSBuild version. Example here is for MSBuild 14.0.

Upvotes: 6

Related Questions