.NET8控制台项目中获取目标exe的MSBuild常量咨询
.NET 8控制台项目PostBuildEvent中获取目标EXE的MSBuild常量
问题说明
在.NET 8控制台项目的PostBuildEvent中使用$(TargetPath)调用signtool时,该变量指向的是.dll文件而非实际的.exe启动文件。虽然对业务核心.dll签名合理,但需要找到能直接获取目标exe路径的MSBuild内置常量,替代当前手动拼接路径的实现:
echo "$(SignToolPath)signtool.exe" sign /d "$(TargetPath)" /fd SHA256 /du "https://www.xyz.co.uk" /f "d:\My Certificate.pfx" /p "password" /t "http://timestamp.sectigo.com" /v "$(OutDir)" echo "$(SignToolPath)signtool.exe" sign /d "$(OutDir)\$(TargetFramework)\$(AssemblyName).exe" /fd SHA256 /du "https://www.xyz.co.uk" /f "d:\My Certificate.pfx" /p "password" /t "http://timestamp.sectigo.com" /v "$(OutDir)"
查看MSBuild配置后,发现规则明确:.NETCoreApp/.NETStandard项目即使输出类型为exe,也会强制将TargetExt设为.dll:
<!-- Force .dll extension for .NETCoreApp and .NETStandard projects even if output type is exe. --> <TargetExt Condition="'$(TargetExt)' == ''">.dll</TargetExt> <PropertyGroup> <TargetExt Condition="'$(TargetExt)' == '' and '$(OutputType)'=='exe'">.exe</TargetExt> <TargetExt Condition="'$(TargetExt)' == '' and '$(OutputType)'=='winexe'">.exe</TargetExt> <TargetExt Condition="'$(TargetExt)' == '' and '$(OutputType)'=='appcontainerexe'">.exe</TargetExt> <TargetExt Condition="'$(TargetExt)' == '' and '$(OutputType)'=='library'">.dll</TargetExt> <TargetExt Condition="'$(TargetExt)' == '' and '$(OutputType)'=='module'">.netmodule</TargetExt> <TargetExt Condition="'$(TargetExt)' == '' and '$(OutputType)'=='winmdobj'">.winmdobj</TargetExt> </PropertyGroup>
解决方案
适用的MSBuild内置属性
直接使用**$(AppHostPath)**即可获取宿主exe的完整路径,这是.NET Core/.NET 5+项目专门用于指向启动器exe的内置变量,无需手动拼接路径。
优化后的脚本
echo "$(SignToolPath)signtool.exe" sign /d "$(TargetPath)" /fd SHA256 /du "https://www.xyz.co.uk" /f "d:\My Certificate.pfx" /p "password" /t "http://timestamp.sectigo.com" /v "$(OutDir)" echo "$(SignToolPath)signtool.exe" sign /d "$(AppHostPath)" /fd SHA256 /du "https://www.xyz.co.uk" /f "d:\My Certificate.pfx" /p "password" /t "http://timestamp.sectigo.com" /v "$(OutDir)"
补充说明
.NET 8控制台项目默认生成两类核心文件:
- 承载业务逻辑的
$(AssemblyName).dll:$(TargetPath)指向的就是该文件 - 作为启动入口的宿主exe:
$(AppHostPath)直接指向该文件
这就是$(TargetPath)指向.dll的原因——MSBuild对这类项目优先标记业务程序集,而启动器exe则通过专门的属性暴露。
内容的提问来源于stack exchange,提问作者Andrew Truckle
相关产品推荐
相关产品推荐

