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

Ubuntu 20.04.2中.NET 3.1项目安装Microsoft.CodeAnalysis仍报错

问题描述

我有一个在Windows系统VS Code中运行正常的.NET项目,在Ubuntu 20.04.2的VS Code中按F5运行时,出现以下编译错误:

CSC : error CS8032: An instance of analyzer System.Text.Json.SourceGeneration.JsonSourceGenerator cannot be created from /home/one/.nuget/packages/system.text.json/6.0.6/analyzers/dotnet/roslyn3.11/cs/System.Text.Json.SourceGeneration.dll : Could not load file or assembly 'Microsoft.CodeAnalysis, Version=3.11.0.0, Culture=neutral, PublicKeyToken=****'. The system cannot find the file specified.. [/home/one/github/fhir/Foo.Service/Foo.Service/Foo.Service.csproj]
CSC : error CS8032: An instance of analyzer System.Text.Json.SourceGeneration.JsonSourceGenerator cannot be created from /home/one/.nuget/packages/system.text.json/6.0.6/analyzers/dotnet/roslyn4.0/cs/System.Text.Json.SourceGeneration.dll : Could not load file or assembly 'Microsoft.CodeAnalysis, Version=3.11.0.0, Culture=neutral, PublicKeyToken=******'. The system cannot find the file specified.. [/home/one/github/fhir/Foo.Service/Foo.Service/Foo.Service.csproj]

已确认相关文件存在:

  • System.Text.Json分析器文件(roslyn3.11和roslyn4.0版本)均存在于NuGet缓存中
  • 项目csproj文件正常
  • 已通过VS Code的NuGet安装了Microsoft.CodeAnalysis 3.11.0版本,且该包已存在于系统NuGet缓存中,但错误依旧。
解决方案

1. 确保项目已正确引用Microsoft.CodeAnalysis包

全局安装NuGet包不会自动添加到项目引用中,需要将包直接安装到项目:

  • 打开VS Code的NuGet包管理器,找到Microsoft.CodeAnalysis 3.11.0版本,选择当前项目进行安装;
  • 或者手动编辑项目的.csproj文件,添加以下引用:
<PackageReference Include="Microsoft.CodeAnalysis" Version="3.11.0" PrivateAssets="all" />

添加后执行dotnet restore命令刷新依赖。

2. 检查并匹配.NET SDK版本

System.Text.Json 6.0.6依赖的Roslyn版本与.NET 6 SDK兼容,确认Ubuntu系统中已安装正确的.NET SDK版本:

  • 执行dotnet --list-sdks查看已安装的SDK;
  • 如果缺少.NET 6 SDK,通过以下命令安装:
sudo apt update
sudo apt install dotnet-sdk-6.0

安装完成后,确保项目的.csproj中TargetFramework指定为net6.0(或对应兼容版本)。

3. 清理项目缓存并重建

缓存文件可能导致依赖加载异常,执行以下步骤:

  1. 删除项目目录下的bin和obj文件夹;
  2. 清理NuGet本地缓存:
dotnet nuget locals all --clear
  1. 重新恢复依赖并构建项目:
dotnet restore
dotnet build

4. 更新VS Code的C#扩展(OmniSharp)

VS Code的C#扩展依赖Roslyn组件,旧版本可能无法兼容所需的Microsoft.CodeAnalysis版本:

  • 打开VS Code的扩展面板,找到C#扩展(由Microsoft发布),点击更新按钮;
  • 更新完成后重启VS Code,再尝试运行项目。

5. 临时禁用源生成器(仅用于排查)

如果以上方法无效,可以临时禁用System.Text.Json的源生成器来验证是否是分析器的问题,在.csproj中添加:

<PropertyGroup>
  <JsonSourceGenerationMode>None</JsonSourceGenerationMode>
</PropertyGroup>

注意:这只是临时排查手段,不建议长期使用,因为会失去源生成带来的性能优化。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 11:15:58