Delete a file (image) added to listview and imagelist
I am using the following code to load the ListView and ImageList:
Code:
'Populate screenshots
ScrnShtDirLbl.Text = ScrnShts
ToolTip1.SetToolTip(ScrnShtDirLbl, ScrnShts)
ScrnShtsLst.Items.Clear()
ImageList1.Images.Clear()
For Each item In IO.Directory.GetFiles(ScrnShts)
ImageList1.Images.Add(item, LoadImage(item).Clone)
'Img.Dispose()
Dim fi As New IO.FileInfo(item)
Dim It As New ListViewItem With {
.Text = fi.Name,
.Tag = item,
.ImageKey = item
}
ScrnShtsLst.Items.Add(It)
Next
Code:
Function LoadImage(filepath As String) As Image
Using imgTemp As New Bitmap(filepath) ' Temporarily load image into a variable rather than into the ImageList directly.
Return imgTemp.Clone
imgTemp.Dispose()
End Using
End Function
Then to delete selected items:
Code:
Private Sub DeleteScrnShtBtn_Click(sender As Object, e As EventArgs) Handles DeleteScrnShtBtn.Click
If ScrnShtsLst.CheckedItems.Count > 0 Then
For Each itm As ListViewItem In ScrnShtsLst.CheckedItems
Try
'ImageList1.Images.Keys.Remove(itm.Tag.ToString)
ImageList1.Images.RemoveByKey(itm.Tag.ToString)
'ImageList1.Images.Item(itm.Index).Dispose()
'ImageList1.Images.RemoveAt(itm.Index)
ScrnShtsLst.Items.Remove(itm)
'ScrnShtsLst.Items.Item(itm.Index).Remove()
Application.DoEvents()
'IO.File.Delete(itm.Tag.ToString)
'FilesToDelete.Add(itm.Tag.ToString)
My.Computer.FileSystem.DeleteFile(itm.Tag.ToString, FileIO.UIOption.OnlyErrorDialogs, FileIO.RecycleOption.SendToRecycleBin)
Catch ex As Exception
My.Computer.Clipboard.SetText(ex.Message)
MsgBox(ex.Message)
End Try
Next
ReLoadLists()
End If
The Try/Catch Ex.Message is
Quote:
The process cannot access the file 'C:\Users\'User'\AppData\Roaming\.minecraft\screenshots\2022-12-03_06.44.22.png' because it is being used by another process.
The code above is from several posts such as this, this, and this. Nothing seems to work. Please help.