Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/redis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在windows应用程序中附加到json文件_C#_Json_Json.net - Fatal编程技术网

C# 在windows应用程序中附加到json文件

C# 在windows应用程序中附加到json文件,c#,json,json.net,C#,Json,Json.net,我已经使用newtonsoft在windows应用程序中创建了一个Json格式的文件。代码正在运行,Json正在创建中。但是我想将新文件附加到旧的Json文件中,现在它正在替换。这是我的代码 List<DeviceData> tempDate = new List<DeviceData>(); DeviceData D = new DeviceData(); D.deviceId = St_Id.ToString(); D.ansId = AnswerStr; tempD

我已经使用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);
List tempDate=new List();
DeviceData D=新的DeviceData();
D.deviceId=St_Id.ToString();
D.ansId=AnswerStr;
添加(D);
字符串ans=JsonConvert.SerializedObject(tempDate,Formatting.Indented);
System.IO.File.WriteAllText(@“E:\”+“device.json”,ans);

任何人都可以帮忙。提前谢谢。

使用
文件。附加所有行(示例已打开)

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


BTW:您应该考虑文件内容的反序列化。

< P>根据文档,方法WreEultTress创建一个新文件,将指定的字符串写入文件,然后关闭文件。如果目标文件已存在,则会覆盖该文件

要实现您想要的,您需要检查文件是否存在

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

您好,很抱歉格式有一些错误。字符串作为[{“deviceId”:“2”,“ansId”:“2”,“date”:“2014-11-10T15:30:58.7717853+05:30”}][{“deviceId”:“4”,“ansId”:“1”,“date”:“2014-11-10T15:31:00.8717853+05:30”}]追加到device.json,但是如何获得文件顶部和末尾的括号[]?