如何从picturebox中释放图片,以便在VB.NET中删除图片文件

问题描述 投票:1回答:1

我在ThePic表格上有一个图片框PicViewer,它使用以下代码从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))上的错误。如何从我的表单中删除图片文件以便实际删除它?

.net vb.net image file-io picturebox
1个回答
0
投票

我更喜欢使用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()

所以你不需要发布它。

© www.soinside.com 2019 - 2024. All rights reserved.