I'm trying to deal with JSON using standard C# libraries. I want to save some data from my program for further use. I decided to save them in JSON format. I got that every time a new array is added to the file. How do I make sure new elements are added to the old array instead? I can't understand what needs to be fixed.
Here is an example of serialization:
private static void writeDeviceInfoInLog(string ipNum, string portNum, string deviceNum)
{
DeviceTCP device1 = new DeviceTCP(ipNum, portNum, deviceNum);
DeviceTCP device2 = new DeviceTCP(ipNum, portNum, deviceNum);
DeviceTCP[] devices = new DeviceTCP[] { device1, device2 };
DataContractJsonSerializer jsonFormatter = new DataContractJsonSerializer(typeof(DeviceTCP[]));
using (FileStream fs = new FileStream("0.json", FileMode.Append))
{
jsonFormatter.WriteObject(fs, devices);
}
}
Here is the output file:
[{
"IpDevice":"1","NumberDevice":"3","PortDevice":"2"
},{
"IpDevice":"1","NumberDevice":"3","PortDevice":"2"
}]
[{
"IpDevice":"1","NumberDevice":"3","PortDevice":"2"
},{
"IpDevice":"1","NumberDevice":"3","PortDevice":"2"
}]
FileMode.Appendonly appends to the file. it knows nothing about the JSON. you'll have to process the json in and then add itfs.Seek(-1, SeekOrigin.End), to overwrite the closing array character and write a comma character into the file stream. Then serialize your JSON not to the file stream, but first into a MemoryStream, afterwards set memory stream position to one to ignore the new start array character, and finally call MemoryStream.CopyTo to append it to the file.