MSBuild 提供引用项目文件名以及与项目相关的其他属性的保留属性。 可以在项目文件本身中使用项目的名称或位置,而无需创建自己的属性值。 有关保留属性的详细信息,请参阅 MSBuild 保留属性和已知属性。
先决条件
使用 MSBuild 生成的 Visual Studio 项目。
使用预留项目属性
MSBuild 提供了一些可以在项目文件中使用的保留属性,而无需每次定义它们。 例如,保留属性 MSBuildProjectName 提供对项目文件名的引用。 保留属性 MSBuildProjectDirectory 提供对项目文件位置的引用。
使用保留属性的优点是项目文件名的任何更改都会自动合并。 下次生成项目时,输出文件和其他使用属性的文件名会自动更新为新名称。
若要使用项目属性,请在项目文件中引用属性时使用 $() 表示法,就像引用任何属性一样。 例如:
<CSC Sources = "@(CSFile)"
OutputAssembly = "$(MSBuildProjectName).exe"/>
</CSC>
有关在文件或项目引用中使用特殊字符的信息,请参阅 MSBuild 特殊字符。
注释
不能在项目文件中重新定义保留属性。
使用 MSBuildProjectName 指定输出文件名
以下示例项目文件将项目名称引用为保留属性,以指定输出的名称。
<Project DefaultTargets = "Compile">
<!-- Specify the inputs -->
<ItemGroup>
<CSFile Include = "consolehwcs1.cs"/>
</ItemGroup>
<Target Name = "Compile">
<!-- Run the Visual C# compilation using
input files of type CSFile -->
<CSC Sources = "@(CSFile)"
OutputAssembly = "$(MSBuildProjectName).exe" >
<!-- Set the OutputAssembly attribute of the CSC task
to the name of the project -->
<Output
TaskParameter = "OutputAssembly"
ItemName = "EXEFile" />
</CSC>
<!-- Log the file name of the output file -->
<Message Text="The output file is @(EXEFile)"/>
</Target>
</Project>
使用 MSBuildProjectDirectory 创建文件的完整路径
以下示例项目文件使用 MSBuildProjectDirectory 保留属性创建项目文件位置中文件的完整路径。 此示例使用 属性函数语法 调用静态 .NET Framework 方法 System.IO.Path.Combine。
<Project>
<!-- Build the path to a file in the root of the project -->
<PropertyGroup>
<NewFilePath>$([System.IO.Path]::Combine($(MSBuildProjectDirectory), `BuildInfo.txt`))</NewFilePath>
</PropertyGroup>
</Project>