gpt4 book ai didi

c# - 在 Windows 应用程序中附加到 json 文件

转载 作者:行者123 更新时间:2023-11-30 22:02:30 24 4
gpt4 key购买 nike

我已经使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com