Append to a json file in windows application

醉酒当歌 提交于 2019-12-11 03:13:33

问题


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);

can any one help.Thanks in advance.


回答1:


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);



回答2:


use File.AppendAllLines docs and example is on http://msdn.microsoft.com/en-us/library/dd383691(v=vs.110).aspx)

System.IO.File.AppendAllLines(@"E:\" + " device.json", ans);

BTW: You should consider about deserialization of file's content.



来源:https://stackoverflow.com/questions/26839654/append-to-a-json-file-in-windows-application

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!