我相信我看到使用緩存行爲使用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);
和我已經驗證不存在創建,不會創建文件未找到異常。我相信某種緩存行爲正在發生,並且想知道如何「重置」所有內容。
我知道這不應該發生,但我真的已經證實了這一點。這就是爲什麼我相信先前的文件現有的是以某種方式被緩存在我的代碼中。我只是沒有看到在哪裏。
不會觸及「緩存行爲」部分,但您確實知道有一種名爲File.Exists()的方法,對不對? http://msdn.microsoft.com/en-us/library/system.io.file.exists(v=vs.110).aspx – 2014-12-03 15:23:08
@WillemvanRumpt我試過使用File.Exists(path),並且還展示了相同的緩存行爲。 – octopusgrabbus 2014-12-03 15:29:30
我不知道在這種情況下的任何緩存行爲。您可能想要發佈額外的代碼以準確顯示發生了什麼(特別是gen_full_yr_image_path()和get_full_yr_image_path()),但我一定會鼓勵您保留File.Exists()檢查以支持當前實現。 – 2014-12-03 15:32:06