Fix duplicate solution folder creation when adding multiple projects from same directory
When adding multiple projects from the same directory (e.g., dotnet sln add Dir/Proj1.csproj Dir/Proj2.csproj), GenerateIntermediateSolutionFoldersForProjectPath would call solution.AddFolder() for each project without checking if the folder already exists, causing duplicate folder entries.
Changes
-
SolutionAddCommand.cs: Check for existing solution folder before creating new one
- Use
SingleOrDefault()to find existing folder by path - Reuse existing folder if found, create new one only if needed
- Use
-
GivenDotnetSlnAdd.cs: Add test
WhenMultipleProjectsFromSameDirectoryAreAddedSolutionFolderIsNotDuplicated- Validates both projects end up in same solution folder
- Covers .sln and .slnx formats
// Before: Always created new folder, causing duplicates
return solution.AddFolder(GetSolutionFolderPathWithForwardSlashes(relativeSolutionFolderPath));
// After: Reuse existing folder if present
var solutionFolderPath = GetSolutionFolderPathWithForwardSlashes(relativeSolutionFolderPath);
var existingFolder = solution.SolutionFolders.SingleOrDefault(f => f.Path == solutionFolderPath);
return existingFolder ?? solution.AddFolder(solutionFolderPath);
Original prompt
This section details on the original issue you should resolve
<issue_title>[Regression] dotnet sln add with 2 projects on the same directory produces an invalid solution</issue_title>
<issue_description>### Describe the bug
Creating a solution using dotnet sln add with 2 projects presents on the same directory produces a non working solution. The error is the following as when opening the solution in VS2022:
It has been present since when I upgraded to (around) VS 2022 17.14.19. I can reproduce with the last VS 2022 maintenance version 17.14.21, which has dotnet SDK 9.0.308 and 8.0.416. I have a linux box that ships with older SDKs 9.0.107/8.0.117 where I don't reproduce.
To Reproduce
Uncompress TestDotnetSlnAddProject.zip and run bootstrap.ps1 which does:
dotnet new sln --name TestDotnetSlnAddProject --force
dotnet sln TestDotnetSlnAddProject.sln add TestDotnetSlnAddProject/TestDotnetSlnAddProject.csproj TestDotnetSlnAddProject/TestDotnetSlnAddProject2.csproj
dotnet restore TestDotnetSlnAddProject.sln
Exceptions (if any)
dotnet restore outputs:
Solution file error MSB5004: The solution file has two projects named "TestDotnetSlnAddProject".
Opening in Visual Studio:
"The solution folder
Further technical details
details of dotnet --info
- Fixes dotnet/sdk#51970
✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.
Tested in codespaces. The original repro only created one solution folder and I was able to build the project.