问题
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