【问题标题】:WPF: Save and read Json file in Documents folderWPF:在 Documents 文件夹中保存和读取 Json 文件
【发布时间】:2021-09-16 01:05:07
【问题描述】:

我正在制作一个简单的 WPF 程序:

如何将 json 字符串保存在 Documents 文件夹中的 data.json 文件中并使用 Json.NET 将其读回?

我的代码:

    public void SerializeTest()
    {
        for (int i = 0; i < 3; i++)
        {
            Product product = new Product();
            product.Name = "Item " + i;

            productList.Add(product);
        }

        json = JsonConvert.SerializeObject(productList, Formatting.Indented);
    }

【问题讨论】:

    标签: json wpf save


    【解决方案1】:

    我猜你在找什么

    Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    

    您可以使用它并附加到您想要的文件。

    json = JsonConvert.SerializeObject(productList, Formatting.Indented);
     
    string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\ExampleFolder\\ExampleSubFolder\\data.json";
            try
            {
                    File.WriteAllText(path, json);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多