オブジェクトをファイルに保存するメソッドがあります。オブジェクトは何度も変更され、保存されます。問題は、オブジェクトを 2 回目に同じファイルに保存しようとすると、UnautorizedAccessException が発生することです。コードは次のとおりです。
public void Save(string path)
{
string fileName = String.Format("{0}\\{1}", path, DataFileName);
using (FileStream fs = new FileStream(fileName, FileMode.Create))
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(fs, this);
File.SetAttributes(fileName, FileAttributes.Hidden);
}
}
最も興味深いのは、行にコメントすると
File.SetAttributes(fileName, FileAttributes.Hidden);
問題が消える。どうして?そして、どうすればこの問題を解決できますか?