Search code examples
c#jsonwpfjson.netfilestream

Json format broke after saving


So I have an application with a List. I store this List in a json file and while the application is running I make changes to the list and save it as .json file on disk.

Before the application is closed by the user I would like to reset some values. On that save right before the application is close the format of the json is not saved correctly. Resulting in a invalid json file.

Close:

private void btnClose_Click(object sender, RoutedEventArgs e)
{
   foreach (var customer in _currentCustomers) {
      customer.State = TransferState.None;
      customer.NextScan = String.Empty;
   }
   WriteCustomerList();
   this.Close();
}

WriteCustomerList Method:

try
{
      using (var fileStream = new FileStream(_appConfigLocation, FileMode.OpenOrCreate, FileAccess.Write))
     {
        using (var br = new BinaryWriter(fileStream))
        {

           br.Write(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(_currentCustomers)));

         }
      }
}
catch (Exception ex)
{
        System.Windows.MessageBox.Show("Failed to write customer list./n/n" + ex.Message, "Error!");
}

Correct Json:

[{
    "Username": "xxxxx",
    "Password": "xxxx",
    "RelationNumber": "xxxx",
    "State": 3,
    "NextScan": "",
    "Interval": 1
}]

Json After closing:

[{
    "Username": "xxx",
    "Password": "xxxx",
    "RelationNumber": "xxxx",
    "State": 3,
    "NextScan": "",
    "Interval": 1
}]26","Interval":1}]

Solution

  • You don't truncate file so previous content is still there (resulting in whatever is after first ]).

    In your case using File.WriteAllText would be safer and shorter solution:

    File.WriteAllText(_appConfigLocation,
         JsonConvert.SerializeObject(_currentCustomers));
    

    If you need more control - use FileMode.Truncate or other approaches recommended in How to truncate a file in c#?.