2011-05-11 12 views
4

我希望在PictureBox中顯示圖像,從文件中加載圖像。該文件會被定期覆蓋,所以我無法保持文件被鎖定。我開始這樣做:如何在不保持文件鎖定的情況下從文件加載圖像?

pictureBox.Image = Image.FromFile(fileName);

然而,這保持鎖定該文件。然後我試圖通過流閱讀:

using (System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read)) 
{ 
    pictureBox.Image = Image.FromStream(fs); 
} 

這不鎖文件,但確實原因將在後面拋出的異常; MSDN表示該流必須在圖像的整個生命週期內保持打開狀態。 (該例外包括「不可讀取封閉文件」或類似消息的消息)。

如何從文件加載圖像,然後再沒有對該文件的引用?

回答

9

對不起回答我自己的問題,但我認爲這對我自己來說太有用了。

訣竅是將數據從文件流中複製到內存流中,然後將其加載到圖像中。然後可以安全地關閉文件流。

using (System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read)) 
{ 
    System.IO.MemoryStream ms = new System.IO.MemoryStream(); 
    fs.CopyTo(ms); 
    ms.Seek(0, System.IO.SeekOrigin.Begin); 
    pictureBox.Image = Image.FromStream(ms); 
} 
2

對於那些低於Framework 4.0中工作,這是我做的:

Using fs As New System.IO.FileStream(cImage, IO.FileMode.Open, IO.FileAccess.Read) 
      Dim buffer(fs.Length) As Byte 
      fs.Read(buffer, 0, fs.Length - 1) 
      Using ms As New System.IO.MemoryStream 
       ms.Write(buffer, 0, buffer.Length - 1) 
       picID.Image = Image.FromStream(ms) 
      End Using 
     End Using 
相關問題