2014-12-03 82 views
0

我相信我看到使用緩存行爲使用FileStream

try catch finally

與FileStream對象 「緩存行爲」。

我想一個PictureBox圖像保存到看起來像這樣的網絡文件路徑:

\\img_srv\permitimages\2014\Building\4454-1.tif

這裏是進行保存和遞增的文件名代碼:

public void save_file_name() 
{ 
    gen_full_yr_image_path(); 
    string image_path = get_full_yr_image_path(); 
    bool does_file_exist = true; 
    FileStream test_file = null; 

    while (does_file_exist) 
    { 
     try 
     { 
      test_file = new FileStream(image_path, FileMode.Open, FileAccess.Read); 
      test_file.Close(); 
      test_file.Dispose(); 
      test_file = null; 

      gen_image_file_name(); 
      gen_full_yr_image_path(); 
      image_path = get_full_yr_image_path(); 
     } 

     catch 
     { 
      does_file_exist = false; 
      test_file = new FileStream(image_path, FileMode.CreateNew, FileAccess.Write); 
      test_file.Close(); 
      test_file.Dispose(); 
      test_file = null; 
      m_scanned_pic.Image.Save(image_path, System.Drawing.Imaging.ImageFormat.Tiff); 
     } 

     finally 
     { 
      if (null != test_file) 
      { 
       test_file.Close(); 
       test_file.Dispose(); 
      } 
     } 
    } 
} 

我看到的行爲如下:

如果\\img_srv\permitimages\2014\Building\4454-1.tif不存在,嘗試打開文件導致異常。這是預期的行爲。

但是,如果\\img_srv\permitimages\2014\Building\4454-1.tif確實存在,未來增量文件名

\\img_srv\permitimages\2014\Building\4454-2.tif

test_file = new FileStream(image_path, FileMode.Open, FileAccess.Read);

和我已經驗證不存在創建,不會創建文件未找到異常。我相信某種緩存行爲正在發生,並且想知道如何「重置」所有內容。

我知道這不應該發生,但我真的已經證實了這一點。這就是爲什麼我相信先前的文件現有的是以某種方式被緩存在我的代碼中。我只是沒有看到在哪裏。

+1

不會觸及「緩存行爲」部分,但您確實知道有一種名爲File.Exists()的方法,對不對? http://msdn.microsoft.com/en-us/library/system.io.file.exists(v=vs.110).aspx – 2014-12-03 15:23:08

+0

@WillemvanRumpt我試過使用File.Exists(path),並且還展示了相同的緩存行爲。 – octopusgrabbus 2014-12-03 15:29:30

+0

我不知道在這種情況下的任何緩存行爲。您可能想要發佈額外的代碼以準確顯示發生了什麼(特別是gen_full_yr_image_path()和get_full_yr_image_path()),但我一定會鼓勵您保留File.Exists()檢查以支持當前實現。 – 2014-12-03 15:32:06

回答

1

test_file.Close();添加到catch後已更正此問題,該文件已在原始帖子中更新。我已經看到與未關閉的數據庫遊標相似的行爲。

+0

你可能應該讓自己熟悉'使用'。現在你的處置代碼是迷信的處置模式。關閉3次沒有好處。 – usr 2014-12-25 18:28:55

+0

謝謝。我會記下來,下週看看。 – octopusgrabbus 2014-12-25 18:40:49