2010-09-23 33 views
1

我加載一個文件:c#ASP.NET如何刪除另一個進程「正在使用」的文件?

System.Drawing.Image img = System.Drawing.Image.FromFile(FilePath); 

現在我想保存圖片:

img.Save(SavePath); 

這工作。除非FilePath == SavePath,然後決定給我的錯誤:

System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+. 

於是,我就刪除該文件,打開後立即:

System.Drawing.Image img = System.Drawing.Image.FromFile(FilePath); 
File.Delete(FilePath); 

,它給我的錯誤:

System.IO.IOException: The process cannot access the file 'filename.jpg' because it is being used by another process. 

所以...... 我如何修改現有的文件,這就是「使用」時,其不被任何人使用?

回答

1

既可以使用存儲器流或把它放在byte []數組

http://www.vcskicks.com/image-to-byte.php

+0

此頁幫了不少忙。 – Justin808 2010-09-23 01:45:51

+0

@ Justin808如果它幫助你應該投票。 – 2010-09-23 02:06:47

+0

很高興我幫了忙。 – 2010-09-23 04:15:38

2

的圖像將保持鎖定,直到它被設置(See here)。

The file remains locked until the Image is disposed.

你必須保存圖像別的地方(或複製其內容出來),然後通過使用using條款處置打開的圖像。

例子:

using(Image image1 = Image.FromFile("c:\\test.jpg")) 
{ 
    image1.Save("c:\\test2.jpg"); 
} 

System.IO.File.Delete("c:\\test.jpg"); 
System.IO.File.Move("c:\\test2.jpg", "c:\\test.jpg"); 
+0

爲什麼在天堂名稱文件保持鎖定?它打開,讀入內存,並關閉?使Image類型成爲PITA。 – Justin808 2010-09-23 01:45:01

+0

@ Justin808:我不確定推理,但文檔說明如此設計,請參閱我上面的編輯。 – 2010-09-23 01:46:43

+0

這有效,但下面的鏈接解釋瞭如何在不使用臨時文件的情況下執行此操作。 – Justin808 2010-09-23 07:10:57

相關問題