クラスのリストをバイナリファイルに保存し、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();
}
}
}
私のプログラムのある時点で、ファイルは "破壊され"ます。これがファイルに書き込む権利を持つ唯一の方法ですので、私はこの方法が問題だと思います。
私は、Filestreamがフラッシュされて閉じられるとき、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