2013-08-07 64 views
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); 

問題就消失了。怎麼會?我該如何解決這個問題?

+0

您是否關閉第一次保存的流? – Botonomous

+0

反正你的'SetAttributes()'調用不應該在''using'之外嗎? – itsme86

+0

取消隱藏,保存,重新隱藏。 –

回答

4

MSDN說,這大約FileMode.Create

指定操作系統應創建一個新的文件。如果 文件已經存在,它將被覆蓋。這需要 FileIOPermissionAccess.Write權限。 FileMode.Create相當於 要求如果該文件不存在,使用CreateNew; 否則,請使用截斷。 如果該文件已存在但是隱藏文件 ,則會引發UnauthorizedAccessException異常。

這正是你所看到的。因此,解決方案似乎要麼使用不同的模式,要麼按照評論中的建議,取消隱藏 - >保存 - >隱藏。

+1

謝謝,現在工作正常。 RTFM問題=) – KorsaR