26

I have a series of properties I need to set in ~15 projects. Is there a way to put these properties in a single file and have all the project files reference the one file using some sort of import directive rather than duplicating the properties in each project file?

EDIT: To clarify, I'm talking about <PropertyGroup> elements within the csproj file. All the projects need the same series of <PropertyGroup> settings. These elements set properties like DebugSymbols or DefineDebug, and are not used for referencing source files.

Daniel Schaffer
  • 56,753
  • 31
  • 116
  • 165

3 Answers3

29

The <Import> element can be used for this, similar to how custom targets files are used.

The reusable file should look like this:

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    <PropertyGroup>
        <!-- Properties go here -->
    </PropertyGroup>
</Project>

Note that having the root Project element with the xmlns declaration is required - VS won't load a project referencing this file without it.

I've saved my properties settings in my solution directory as ProjectBuildProperties.targets.

To include the file in other projects, I've added this to the csproj files:

<Import Project="$(SolutionDir)ProjectBuildProperties.targets"/>

And it works!

Daniel Schaffer
  • 56,753
  • 31
  • 116
  • 165
  • 1
    It seems that the current Visual Studio works even without xmlns attribute. (I am not sure when this change happened. We use .NET Core which does not have xmlns even in the csproj files, maybe that is the difference.) – Al Kepp Sep 27 '21 at 18:38
  • See for VS 2022 solution the [answer](https://stackoverflow.com/a/73049280/696355) of @lozzer – H. de Jonge Jan 19 '23 at 09:42
4

Shared properties can go in the Directory.Build.props file. This does not need to be explicitly imported into each csproj, this is all taken care of by MSBuild, including a hierarchy of props files. Example file content:

<Project>
    <PropertyGroup>
        <DebugSymbols>true</DebugSymbols>
        <DefineDebug>true</DefineDebug>
    </PropertyGroup>
</Project>

For more information see https://learn.microsoft.com/en-us/visualstudio/msbuild/customize-your-build?view=vs-2022#directorybuildprops-and-directorybuildtargets

Lozzer
  • 155
  • 2
  • 12
  • This should be the accepted answer, 10 years later. To have this file easily accessible, you can add a solution folder (via the solution context menu) and add the file there. It will physically still be placed in the solution directory, so the automatic mechanism still works, but you can see it in the IDE. – H. de Jonge Jan 19 '23 at 09:39
2

You can create a shared MSBuild file that can be imported by all projects.

This post discusses this solution and demonstrate it here

KMoraz
  • 14,004
  • 3
  • 49
  • 82