json - WPF:在 Documents 文件夹中保存和读取 Json 文件
问题描述
我正在制作一个简单的 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);
}
解决方案
我想你正在寻找的是
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);
}
推荐阅读
- matlab - 在 Octave 中为 fplot 设置线宽
- python - 使用 Beautiful Soup 选择 HTML 页面值
- php - 在 Laravel 刀片中 @extends 布局与条件如何传递数据
- c# - 覆盖基类的实现,以便从继承的基类函数调用也调用被覆盖的函数
- angular - 离子 3 指令。在 div 上添加自定义属性?
- python - Python 3 中的三向比较字符串
- python - python中的日期时间格式与格式不同
- java - 为什么 Java 中的 hashcode 不使用 long 来存储 hash 值?
- botframework - 尝试了来自 Microsoft.Bot.Sample.AadV2Bot 的代码,但甚至在本地获取 AADSTS50011(回复 url 不匹配)
- java - Web 应用程序是否将代码隐式包装在禁止 JVM 优化的 try-catch 块中?