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

使用C# JsonSerializer.Serialize时遇System.Memory缺失问题求助

问题:System.Text.Json序列化时出现System.Memory文件缺失错误

尝试序列化List<MapPool>对象,已添加System.Text.Json依赖,但执行JsonSerializer.Serialize时触发FileNotFoundException,提示找不到System.Memory, Version=4.0.1.1。

相关代码

private const string MapPoolsFile = @"../../../resources/MapPools.json";
public void JSONSerializerMapPools()
{
    if (File.Exists(MapPoolsFile))
    {
        List<Map> Maps = new List<Map> { new Map(Side.Attack, Side.Deffend, "Inferno"), new Map(Side.Attack, Side.Deffend, "Nuke"), new Map(Side.Attack, Side.Deffend, "Mirage") };
        List<MapPool> MapPools = new List<MapPool> { new MapPool("CSGO BIG3", Maps) };
        string json = JsonSerializer.Serialize(MapPools);
        Console.WriteLine(json);
        File.WriteAllText(MapPoolsFile, json);
    }
    else
    {
        Console.WriteLine("File not found");
    }
}

报错信息

Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly 'System.Memory, Version=4.0.1.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies. The system cannot find the file specified.
   at System.Text.Json.JsonSerializerOptions.GetDefaultSimpleConverters()
   at System.Text.Json.JsonSerializerOptions.RootBuiltInConverters()
   at System.Text.Json.JsonSerializerOptions.InitializeForReflectionSerializer()
   at System.Text.Json.JsonSerializer.GetTypeInfo(JsonSerializerOptions options, Type runtimeType)
   at System.Text.Json.JsonSerializer.Serialize[TValue](TValue value, JsonSerializerOptions options)
   at Datalaag.DataProvider.JSONSerializerMapPools() 

解决方法

  • 检查并更新System.Memory包:打开NuGet包管理器,搜索System.Memory,安装或更新到与项目兼容的版本。如果是.NET Core 3.0及以上版本,该包通常随框架自带;若为.NET Framework项目,则需手动安装匹配版本。
  • 添加程序集重定向(仅.NET Framework):在项目的app.config或web.config中添加以下配置,让运行时自动重定向到已安装的System.Memory版本:
    <configuration>
      <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
          <dependentAssembly>
            <assemblyIdentity name="System.Memory" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
            <bindingRedirect oldVersion="0.0.0.0-4.0.1.1" newVersion="4.0.1.2" /> <!-- 替换为你实际安装的版本号 -->
          </dependentAssembly>
        </assemblyBinding>
      </runtime>
    </configuration>
    
  • 清理重建项目:删除项目的bin和obj目录,重新生成解决方案,确保所有依赖项正确复制到输出目录。
  • 确认目标框架兼容性:如果是.NET Framework项目,建议使用4.7.2及以上版本;若条件允许,升级到.NET Core/.NET 5+可避免此类依赖问题。
  • 检查输出目录文件:查看项目输出目录(如bin/Debug)中是否存在System.Memory.dll,若缺失,确认NuGet包是否正确安装,必要时手动复制对应版本的dll文件到输出目录。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 13:55:12