DDulla
DDulla

Reputation: 679

Disposing dynamically created picturebox to release file lock?

I am trying to release the file lock on some images so i can move them into an archive folder.

The program loops through the images and adds pictureboxes to a flowlayout panel. After the operation is completed i dispose of the flowlayout panel, and then archive the files.

It is my understanding that disposing the panel will dispose of the picture boxes inside of it, however when i try the move operation i get a IOException Access Denied.

Code:

  Dim ImagesInFolder As New List(Of Image)()
    For Each JPEGImages As String In Directory.GetFiles(ExportDir.FullName, "*.jpg")
        ImagesInFolder.Add(Image.FromFile(JPEGImages))
    Next
    Dim x As Integer = 0
    Dim y As Integer = 0
    For i As Integer = 0 To ImagesInFolder.Count - 1
        Dim _image As New PictureBox()
        _image.Location = New Point(x, y)
        x += 50
        _image.Image = ImagesInFolder(i)
        _image.Size = New Size(50, 50)
        _image.SizeMode = PictureBoxSizeMode.StretchImage
        FlowLayoutPanel1.Controls.Add(_image)
    Next

Later in the application:

    FlowLayoutPanel1.Dispose()
    Directory.Move(CurrentFolder, ArchiveFolder)

Upvotes: 1

Views: 1033

Answers (1)

Reza Aghaei
Reza Aghaei

Reputation: 125257

The problem is Because of loading image using Image.FromFile(file).

When you load image using Image.FromFile(file) the file will be locked.

To avoid locking file you can load your images using Image.FromStream.

Code:

Dim filePath = "path to your image file"
Dim contentBytes = File.ReadAllBytes(filePath)
Dim memoryStream As New MemoryStream(contentBytes)
Dim image= Image.FromStream(memoryStream)
YourPictureBox.Image = image

Upvotes: 3

Related Questions