在Windows应用程序中附加到json文件 [英] Append to a json file in windows application

查看:61
本文介绍了在Windows应用程序中附加到json文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用newtonsoft在Windows应用程序中创建了一个Json格式的文件.代码可以正常工作,并且json可以正常创建.但是我想将新文件附加到旧的json文件中,现在它正在替换.这是我的代码

I have created a Json format file in windows application using newtonsoft.the code is working and the json is creating fine.But I want to append the new file to the old json file,now it is replacing.here is my code

List<DeviceData> tempDate = new List<DeviceData>();
DeviceData D = new DeviceData();
D.deviceId = St_Id.ToString();
D.ansId = AnswerStr;
tempDate.Add(D);
string ans = JsonConvert.SerializeObject(tempDate, Formatting.Indented);
System.IO.File.WriteAllText(@"E:\" + " device.json", ans);

可以帮忙.谢谢.

推荐答案

根据文档,方法writeAllText创建一个新文件,将指定的字符串写入该文件,然后关闭该文件.如果目标文件已经存在,则将其覆盖.

According to the documentation, the method writeAllText Creates a new file, writes the specified string to the file, and then closes the file. If the target file already exists, it is overwritten.

要实现所需的功能,需要检查文件是否存在

To achieve what you want you need to do a check whether the file exists or not

string ans = JsonConvert.SerializeObject(tempDate, Formatting.Indented);
if (File.Exists(@"E:\" + " device.json")
  File.AppendAllText(@"E:\" + " device.json", appendText);
else
  System.IO.File.WriteAllText(@"E:\" + " device.json", ans);

这篇关于在Windows应用程序中附加到json文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆