Close file used by Visual Basic .NET

1

I'm using the following code to grab images from a directory and put it in a ListView:

    For Each arquivos In FileIO.FileSystem.GetFiles(caminho, FileIO.SearchOption.SearchAllSubDirectories, "*.png")
        Dim nome_arq As String = System.IO.Path.GetFileNameWithoutExtension(arquivos)
        imagem.Images.Add(Image.FromFile(arquivos))
        ListView1.LargeImageList = imagem
        ListView1.Items.Add(nome_arq, contador)

And I wanted to use the below command to delete the image that was open in ListView1

     My.Computer.FileSystem.DeleteFile(dicionario(posicao), 
                                        FileIO.UIOption.OnlyErrorDialogs,
                                        FileIO.RecycleOption.SendToRecycleBin,
                                        FileIO.UICancelOption.DoNothing)

The problem is that I get the error message saying that the file is already open and therefore can not be closed.

So my question is how do I remove the image so I can delete it?

    
asked by anonymous 25.06.2018 / 23:58

1 answer

1

The Image.FromFile Method keeps the file open. You should do it another way. You can and greatly improve your code, but to solve your problem, I did as below (based on this response) and it worked fine:

Imports System.IO

Public Class Form1
    Private caminho As String = "C:\teste"

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim xx As Image
        Dim contador As Integer = 0
        ListView1.Clear()
        imagem.Images.Clear()
        For Each arquivos In FileIO.FileSystem.GetFiles(caminho, FileIO.SearchOption.SearchAllSubDirectories, "*.png")

            Using str As Stream = File.OpenRead(arquivos)
                xx = Image.FromStream(str)
                imagem.Images.Add(xx)
            End Using

            ListView1.LargeImageList = imagem
            ListView1.Items.Add(arquivos, contador)
            contador += 1
        Next
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        My.Computer.FileSystem.DeleteFile(ListView1.SelectedItems(0).Text,
                                        FileIO.UIOption.OnlyErrorDialogs,
                                        FileIO.RecycleOption.SendToRecycleBin,
                                        FileIO.UICancelOption.DoNothing)
        ListView1.Clear()
        Button1_Click(Nothing, Nothing)
    End Sub

End Class
    
26.06.2018 / 02:09