我試圖從網站下載圖像並將其放入圖片框中。C#進程無法訪問文件(僅限第二次)
// response contains HttpWebResponse of the page where the image is
using (Stream inputStream = response.GetResponseStream()) {
using (Stream outputStream = File.Open(fileName, FileMode.Create)) {
byte[] buffer = new byte[4096];
int bytesRead;
do {
bytesRead = inputStream.Read(buffer, 0, buffer.Length);
outputStream.Write(buffer, 0, bytesRead);
} while (bytesRead != 0);
}
}
response.Close();
後,下載的圖像被分配到一個PictureBox像這樣:
if (imageDownloaded) {
pictureBox1.Image = Image.FromFile(filePath);
}
這一切工作就像一個魅力第一次,但我運行的代碼我第二次獲得System.IO .IOException:「附加信息:進程無法訪問文件...(文件路徑)...,因爲它正在被另一進程使用。」「。我不知道爲什麼...
我看了其他4個線程,如這個,但他們基本上強調需要關閉流,我這樣做,所以他們都沒有幫助我。
在你推薦使用pictureBox1.Load()
之前,我不能,因爲我需要下載圖像進行進一步的開發。
編輯1:我實際上試圖通過在執行上面的代碼之前放置pictureBox1.Image = null
來處理圖像。它仍然給我一個例外。
可能重複的[如何防止Image.FromFile()方法鎖定文件](http://stackoverflow.com/questions/18250848/how-to-prevent-the-image -fromfile-method-to-lock-the-file) – Chris 2014-10-30 21:34:38
謝謝克里斯,正是我在找的東西。對不起。 – 2014-10-30 21:38:19
不客氣。 – Chris 2014-10-30 21:40:01