Warm tip: This article is reproduced from stackoverflow.com, please click
visual-studio msbuild

Possible to limit the scope of Directory.Build.Props to a single Visual Studio Solution?

发布于 2020-03-27 15:42:28

I have a Visual Studio solution with over 100 projects in it. I want to apply certain settings to all projects, so I used a Directory.Build.Props file and it works great. However, after reading the documentation I just realized that all of the solutions in the sub directories will use those settings too, but I don't want to affect those solutions since I don't maintain them. Is there a way to limit the scope of a Directory.Build.Props file to the current directory, or a particular solution? (Perhaps you can customize the name of the Props file and import it for a particular solution?)

For example, consider a directory structure organized as such:

/code/MySolutionFile.sln
/code/Project001/
/code/Project002/
/code/Project003/
...
/code/Project100/

/code/OtherStuff/OtherStuff.sln
/code/OtherStuff/ProjectA
/code/OtherStuff/ProjectB
/code/OtherStuff/[lots of other solutions somewhere in this directory tree]

I have put my Directory.Build.Props file in the /code directory because I would like to define settings for all projects in /code/MySolutionFile.sln. But I don't want to affect any of the other solutions in subdirectories of the /code folder.

If all else fails I think I could create an empty Directory.Build.Props file and drop it in every directory that contains a solution file except for the one I want mine to apply to. (But this feels like a last resort.)

Questioner
TTT
Viewed
88
TTT 2020-02-11 04:09

Modifying my Directory.Build.props file in this way accomplishes my goal:

<Project>
  <PropertyGroup Condition="$(SolutionFileName) == 'MySolution.sln'">
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
  </PropertyGroup>
</Project>

This works by setting the PropertyGroup to conditionally run the rules. (Note the condition could also be applied to specific rules rather than the group.) In this case I was able to use the name of the solution file to limit the scope of this rule to my desired solution without affecting any others.

One caveat though, the documentation claims that the solution variables are only available when used in the IDE. However, with my limited testing the rules are also correctly applied when I use msbuild from the command line, like this: msbuild.exe MySolution.sln

I tested it from both a VS Developer Command Prompt and a regular Windows Command Prompt, and both still read the $(SolutionFileName) variable properly.