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

WPF使用Json.NET在Documents文件夹读写JSON文件的实现方法

WPF 基于Json.NET实现Documents目录JSON文件读写

所需命名空间引用

  • using Newtonsoft.Json;:Json.NET核心依赖,你现有序列化代码已经用到
  • using System.IO;:系统文件读写操作必备
  • using System;:获取系统特殊目录路径需要用到

完善序列化+JSON保存到Documents目录逻辑

你现有序列化代码是正确的,补充系统Documents目录路径获取、文件写入逻辑即可,完整代码如下:

public void SerializeAndSaveToFile()
{
    // 你原有序列化逻辑
    List<Product> productList = new List<Product>();
    for (int i = 0; i < 3; i++)
    {
        Product product = new Product();
        product.Name = "Item " + i;
        productList.Add(product);
    }
    string json = JsonConvert.SerializeObject(productList, Formatting.Indented);

    // 新增:获取系统Documents目录路径,拼接目标文件路径
    string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    string targetFilePath = Path.Combine(docPath, "data.json");

    // 新增:写入JSON到目标文件,自动创建不存在的文件,已有文件直接覆盖
    File.WriteAllText(targetFilePath, json);
}

上述路径获取逻辑兼容所有Windows版本、不同用户的目录结构,不会出现硬编码路径导致的报错问题。

实现JSON文件读取+反序列化逻辑

public List<Product> ReadJsonFromFile()
{
    string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    string targetFilePath = Path.Combine(docPath, "data.json");

    // 文件不存在时返回空集合,也可以根据需求添加自定义提示、初始化默认数据
    if (!File.Exists(targetFilePath))
    {
        return new List<Product>();
    }

    string jsonContent = File.ReadAllText(targetFilePath);
    return JsonConvert.DeserializeObject<List<Product>>(jsonContent);
}

注意事项

  • 常规WPF项目读写Documents目录不需要额外申请权限,无需额外修改程序清单
  • 如果Product类有特殊序列化规则,可以给类属性添加[JsonProperty]特性指定别名、配置空值处理、日期格式等规则
  • 如果你需要追加数据而非覆盖已有文件,不要直接用File.WriteAllText,可以先读取已有文件反序列化,追加新数据后再序列化写回文件即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 20:54:03