2

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}]
Florian Schaal
  • 2,586
  • 3
  • 39
  • 59
  • Are you writing all of the data each time? If so, `FileMode.OpenOrCreate` could be the problem if the file if longer than the new data you are writing. You probably would want `FileMode.Truncate`. – crashmstr May 28 '15 at 15:31
  • Yes i'm just overwriting the all data each time. – Florian Schaal May 28 '15 at 15:32

1 Answers1

4

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#?.

Community
  • 1
  • 1
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179