保存后Json格式破了

时间:2015-05-28 15:25:14

标签: c# json wpf json.net filestream

所以我有一个带有List的应用程序。我将此List存储在json文件中,当应用程序运行时,我对列表进行更改并将其保存为磁盘上的.json文件。

在用户关闭应用程序之前,我想重置一些值。在应用程序关闭之前的保存时,json的格式未正确保存。导致无效的json文件。

关闭

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方法:

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!");
}

纠正Json:

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

Json关闭后:

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

1 个答案:

答案 0 :(得分:3)

您不会截断文件,因此之前的内容仍然存在(导致首先]之后的任何内容。)

在您的情况下使用File.WriteAllText会更安全,更简短的解决方案:

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

如果您需要更多控制权,请使用FileMode.TruncateHow to truncate a file in c#?中建议的其他方法。