You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在csproj中判断执行环境以规避WiX项目dotnet命令执行错误?

解决WiX 3项目与dotnet命令的兼容性问题

问题背景

我们的解决方案包含多个WiX 3项目,旧式csproj文件中导入Wix.CA.targets时,会导致dotnet restore、dotnet test等命令执行失败。由于新版本Paket依赖dotnet restore,且仓库需要引入.NET 8项目,因此该命令必须正常运行。

经确认,Wix.CA.targets在包还原和单元测试环节并无实际作用,项目实际构建仍通过VS或MSBuild完成,因此希望通过在.csproj中添加条件判断,当检测到是dotnet命令加载项目时,跳过对Wix.CA.targets的导入。

报错信息

执行dotnet restore时的错误输出:

> dotnet restore demo.sln
C:\Program Files (x86)\MSBuild\Microsoft\WiX\v3.x\Wix.CA.targets(42,5): error MSB4062: The "ReadRegistry" task
could not be loaded from the assembly C:\Program Files (x86)\WiX Toolset v3.11\bin\WixTasks.dll. Could not load
 file or assembly 'Microsoft.Build.Utilities, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
'. The system cannot find the file specified. Confirm that the <UsingTask> declaration is correct, that the ass
embly and all its dependencies are available, and that the task contains a public class that implements Microso
ft.Build.Framework.ITask. [C:\Demo\Wix\Wix.csproj]

解决方案

可以通过MSBuild的内置属性判断当前是否由dotnet命令执行,进而条件性导入Wix.CA.targets。具体修改如下:

修改csproj中的导入节点,添加条件判断:

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <WixCATargetsPath Condition=" '$(WixCATargetsPath)' == '' ">C:\Program Files (x86)\MSBuild\Microsoft\WiX\v3.x\Wix.CA.targets</WixCATargetsPath>
    <!-- 其他属性配置 -->
  </PropertyGroup>
  <!-- 其他项目配置节点 -->
  <!-- 仅当非dotnet命令执行时导入Wix.CA.targets -->
  <Import Project="$(WixCATargetsPath)" Condition=" '$(MSBuildRuntimeType)' != 'Core' " />
</Project>

条件说明

  • $(MSBuildRuntimeType)是MSBuild的内置属性:通过dotnet命令运行时,该属性值为Core;通过VS或传统MSBuild运行时,值为Full。
  • 上述条件确保只有在非dotnet命令的场景下才导入Wix.CA.targets,既避免了dotnet命令执行失败,又不影响正常的VS/MSBuild构建流程。

测试验证:修改后执行dotnet restore即可正常完成包还原,VS/MSBuild构建WiX项目时依然会加载必要的目标文件,不影响安装包生成。

内容的提问来源于stack exchange,提问作者Fire Lancer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 14:02:41