DDulla DDulla - 1 year ago 134
Vb.net Question

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.


Dim ImagesInFolder As New List(Of Image)()
For Each JPEGImages As String In Directory.GetFiles(ExportDir.FullName, "*.jpg")
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

Later in the application:

Directory.Move(CurrentFolder, ArchiveFolder)

Answer Source

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.


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