我將我的類的列表保存到二進制文件中,並使用FileStream和BinaryFormatter。BinaryFormatter.Serialize()在FileStream.Flush()和FileStream.Close()之前完成嗎?
private void SaveCustomers()
{
FileStream fs = null;
try
{
fs = new FileStream(Application.StartupPath + dataPath + @"\" + customersFilename, FileMode.Create, FileAccess.Write);
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, customers);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Fehler beim speichern der Besucherdaten", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
if (fs != null)
{
fs.Flush();
fs.Close();
}
}
}
在我的程序中的某個位置,文件被「銷燬」。由於這是唯一有權在文件中寫入的方法,所以我認爲這種方法是個問題。
我的假設是,當文件流被刷新並關閉時,BinaryFormatter沒有完成。
它最近才發生,因爲該文件開始時大約8 MB,它的工作完美無缺。
我對我的假設是否正確?或者它完全不同。
private void LoadCustomers()
{
FileStream fs = null;
try
{
fs = new FileStream(Application.StartupPath + dataPath + @"\" + customersFilename, FileMode.OpenOrCreate, FileAccess.Read);
BinaryFormatter bf = new BinaryFormatter();
customers = (List<Customer>)bf.Deserialize(fs);
if (customers == null) customers = new List<Customer>();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Fehler beim laden der Besucherdaten", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
if (fs != null)
{
fs.Flush();
fs.Close();
}
}
}
最後的代碼是我的讀者。
無論是在你的'finally'塊中的任何內容都會在'try'和'catch'內的所有內容之後執行**。因此'終於'..它發生**最後**。 – ThePerplexedOne
我同意@ThePerplexedOne - 只要你不序列化asyncron數據將被寫入你的文件。但是,你的意思是:「文件被破壞」?錯誤的數據?文件已刪除?有些不同?我的意思是FileMode.Create會創建或覆蓋你的文件,如果我是對的,...如果這是一種日誌文件,我想這不是你想要做的...如果你想追加使用'FileMode.Append '或'FileMode.OpenOrCreate' – TripleEEE
嘗試在寫入之前刪除文件。我遇到了一個問題,我用'FileMode.Create'寫入了一個文件,並且在導致文件保存無效數據之前沒有正確截斷。在寫之前刪除修復它。 – Mats391