2015-05-28 33 views
1

所以我有一个List应用程序。我将这个List存储在一个json文件中,当应用程序正在运行时,我对列表进行更改并将其保存为磁盘上的.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}] 
+0

您是否每次写入所有数据?如果是这样,如果文件的长度超过了正在写入的新数据,FileMode.OpenOrCreate可能会成为问题。你可能会想'FileMode.Truncate'。 – crashmstr

+0

是的,我只是每次覆盖所有的数据。 –

回答

3

你不截断文件,因此以前的内容仍然存在(导致无论是第一]后)。

在使用File.WriteAllText你的情况可能会更安全和更短的解决方案:

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

如果您需要更多的控制 - 使用FileMode.TruncateHow to truncate a file in c#?推荐的其他方法。

+0

啊,这件作品很棒。我会用这两种解决方案来付出代价,看看这里最适合什么。谢谢! –