我已经使用 newtonsoft 在 Windows 应用程序中创建了一个 Json 格式文件。代码正在运行,并且 json 创建正常。但是我想将新文件附加到旧的 json 文件,现在它正在替换。这是我的代码
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 创建一个新文件,将指定的字符串写入该文件,然后关闭该文件。如果目标文件已存在,则将其覆盖。
要实现您想要的效果,您需要检查文件是否存在
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);
关于c# - 附加到 Windows 应用程序中的 json 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26839654/