我在表单 PicViewer
上有一个图片框 ThePic
,使用下面的代码从一组可能的图片名称 (FileNameSt
)存储在PicList
中,其中CurNum为文件名的数组位置:
Private Sub LoadPic(ByVal FileNameSt As String)
Me.ThePic.Load(PixFolderPath & "/" & FileNameSt)
End Sub
一旦用户将图片加载到表单中,他们就可以选择从文件中删除图片。我尝试使用的代码如下:
Private Sub DelButton_Click(sender As System.Object, e As System.EventArgs) Handles DelButton.Click
Dim Resetter As Boolean
Resetter = False
If Not PixLoaded Then Exit Sub 'User has not selected a file to load pics from
If UBound(PicList) = LBound(PicList) Then PixLoaded = False 'Last pic was deleted
Me.ThePic.Image = Nothing
Me.ThePic.Invalidate()
Me.ThePic.Refresh()
If Not PixLoaded Then
Me.ThePic.Image = My.Resources.NoMorePics 'Out of pics picture
Me.ThePic.Refresh()
GoTo Finisher
End If
'Go to the next image available
If CurNum = UBound(PicList) Then
LoadPic(PicList(LBound(PicList)))
Resetter = True
Else
LoadPic(PicList(CurNum + 1))
End If
Finisher:
My.Computer.FileSystem.DeleteFile(PixFolder & "/" & PicList(CurNum))
If Not PixLoaded Then Exit Sub 'Exits if on last pic
LoadPictures(PixFolder) 'Resets PicList array values
If Resetter Then CurNum = LBound(PicList)
End Sub
当用户试图从文件中删除最后一张图片时,我的问题就出现了。出于某种原因,我收到“该进程无法访问文件‘此处的文件名’,因为它正被另一个进程使用。” My.Computer.FileSystem.DeleteFile(PixFolder & "/"& PicList(CurNum))
错误。如何删除我的表单正在使用的图片文件,以便实际删除它?
最佳答案
我更喜欢使用 FileStream
而不是 .Load
Dim strImageFileName As String
strImageFileName = PixFolderPath & "/" & FileNameSt
Dim fs As System.IO.FileStream
fs = New System.IO.FileStream(strImageFileName, System.IO.FileMode.Open, System.IO.FileAccess.Read)
ThePic.Image = System.Drawing.Image.FromStream(fs)
fs.Close()
所以你不需要释放它。
关于.net - 如何从图片框中释放图片以便在 VB.NET 中删除图片文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29585959/