2012年10月3日 星期三

Image.FromFile()無法停止檔案使用中的狀態

temprow.Cells(3).Value = Image.FromFile(destFile)
最好是改成這樣
Dim fs As IO.FileStream
fs = New IO.FileStream(destFile, IO.FileMode.Open, IO.FileAccess.Read)

temprow.Cells(3).Value = Image.FromStream(fs).GetThumbnailImage(100, 100, Nothing, IntPtr.Zero)
fs.Close()

才不會出現destFile一直在使用中而無法更新或刪除

*以下程式會出現記憶體不足的問題
fs As IO.FileStream

fs = New IO.FileStream(destFile, IO.FileMode.Open, IO.FileAccess.Read)
tempImage = Image.FromStream(fs)
fs.Close()

temprow.Cells(3).Value = tempImage.GetThumbnailImage(100, 100, Nothing, IntPtr.Zero)

正確寫法如下:

fs As IO.FileStream

fs = New IO.FileStream(destFile, IO.FileMode.Open, IO.FileAccess.Read)
tempImage = Image.FromStream(fs)
temprow.Cells(3).Value = tempImage.GetThumbnailImage(100, 100, Nothing, IntPtr.Zero)
fs.Close()

原因是FileStream要到tempImage的生命週期結束才可以關閉喔!