How to Append a json file without disturbing the formatting

Your best and most reliable approach would be to not append to the file, but instead, read the entire JSON file and de-serialize to an object, append to the object collection and then serialize the output back to the JSON file.

I created this sample for you (change paths and class accordingly):

var filePath = @"C:\Users\grahamo\Documents\Visual Studio 2013\Projects\WebApplication1\WebApplication1\bin\path.json";
// Read existing json data
var jsonData = System.IO.File.ReadAllText(filePath);
// De-serialize to object or create new list
var employeeList = JsonConvert.DeserializeObject<List<EmployeeDetail>>(jsonData) 
                      ?? new List<EmployeeDetail>();

// Add any new employees
employeeList.Add(new EmployeeDetail()
{
    Name = "Test Person 1"
});
employeeList.Add(new EmployeeDetail()
{
    Name = "Test Person 2"
});

// Update json data string
jsonData = JsonConvert.SerializeObject(employeeList);
System.IO.File.WriteAllText(filePath, jsonData);

As you are new, up-vote or tick as answer if I have helped you out.


There is a CopyTo method on FileStream. So you don't need to read char-by-char, open a file stream and CopyTo to the response stream.

Also I would recommend you to reserialize the file first (using Json.NET, you can simply use dynamic to avoid messing with concrete types), and since it is an array of objects, then add your new object to this array and save it back.

The format will always be correct since you re-save the whole file.

P.S. You probably will not be able to just append since the serialized JSON object in file is "closed" (you have your } ] there), so appending text will not work.

Tags:

C#

File Io

Json