如何在.csproj中定义引用IntermediateOutputPath的自定义属性
解决MSBuild自定义属性引用$(IntermediateOutputPath)为空的问题
问题原因
直接在项目文件开头定义BuildInfoPath时,$(IntermediateOutputPath)还未被MSBuild的默认属性文件(如Microsoft.Common.props)初始化,因此解析为空。若把属性放到Target内,Target是在默认props导入后执行的,能拿到有效值,但ItemGroup属于项目初始评估阶段的元素,无法读取Target内定义的属性。
正确解决方案
方法1:调整自定义属性的定义位置
将自定义PropertyGroup移到导入MSBuild默认属性文件之后,确保$(IntermediateOutputPath)已完成初始化:
<!-- 先导入MSBuild默认属性文件 --> <Import Project="$(MSBuildToolsPath)\Microsoft.Common.props" /> <PropertyGroup> <!-- 此时IntermediateOutputPath已可用,直接拼接路径 --> <BuildInfoPath>$(IntermediateOutputPath)BuildInfo.gen.cs</BuildInfoPath> </PropertyGroup> <Target Name="Date" BeforeTargets="BeforeBuild"> <WriteLinesToFile File="$(BuildInfoPath)" Lines="...."/> </Target> <ItemGroup> <Compile Include="$(BuildInfoPath)" Condition="Exists('$(BuildInfoPath)')"/> </ItemGroup> <!-- 导入MSBuild默认目标文件 --> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
方法2:使用属性函数规范路径拼接(可选)
用MSBuild内置的CombinePath函数拼接路径,既保证路径格式正确,也能确保求值时机正确:
<PropertyGroup> <BuildInfoPath>$([MSBuild]::CombinePath('$(IntermediateOutputPath)', 'BuildInfo.gen.cs'))</BuildInfoPath> </PropertyGroup>
注意事项
如果你的项目文件已经包含Microsoft.Common.props的导入语句,只需将自定义PropertyGroup移到该导入语句之后即可,无需重复添加导入。
内容的提问来源于stack exchange,提问作者greenoldman
相关产品推荐
相关产品推荐

