views:

29

answers:

2

Hello everyone!

I am adding images to a FlowLayoutPanel control via the following code

Dim WithEvents Pedit As DevExpress.XtraEditors.PictureEdit

Private Sub LoadImagesCommon(ByVal fi As FileInfo)
        Pedit = New DevExpress.XtraEditors.PictureEdit
        Pedit.Width = 133
        Pedit.Height = 98
        Pedit.Image = Image.FromFile(fi.FullName)
        Pedit.Properties.SizeMode = DevExpress.XtraEditors.Controls.PictureSizeMode.Zoom
        Pedit.ToolTip = fi.Name
        AddHandler Pedit.MouseClick, AddressOf Pedit_MouseClick
        AddHandler Pedit.MouseEnter, AddressOf Pedit_MouseEnter
        AddHandler Pedit.MouseLeave, AddressOf Pedit_MouseLeave
        FlowLayoutPanel1.Controls.Add(Pedit)
    End Sub

The problem is that i get the following error The process cannot access the file xxxx because it is being used by another process. when i try to delete the images that i loaded on the previous step.

                    FlowLayoutPanel1.Controls.Clear()
                    FlowLayoutPanel1.Refresh()
                    For Each fi As FileInfo In New DirectoryInfo(My.Settings.TempDirectory).GetFiles
                        RemoveHandler Pedit.MouseClick, AddressOf Pedit_MouseClick
                        RemoveHandler Pedit.MouseEnter, AddressOf Pedit_MouseEnter
                        RemoveHandler Pedit.MouseLeave, AddressOf Pedit_MouseLeave
                        File.Delete(fi.FullName)
                    Next

So what am i doing wrong here?

+2  A: 

Image.FromFile actually locks the file it loads and only releases the lock once it is disposed.

The solution is to draw the image into another image’s graphics context (thus effectively copying it) and dispose the original image.

Konrad Rudolph
+1  A: 

Aha! Thank you Konrad.

after some reading, i found another workaround too.

Dim fs As System.IO.FileStream
fs = New System.IO.FileStream(fi.FullName, IO.FileMode.Open, IO.FileAccess.Read)
Pedit.Image = System.Drawing.Image.FromStream(fs)
fs.Close() 

Update: and here is what Konrad suggested. For all the newbies out there, just like me :)

 Dim imgTemp As System.Drawing.Image  
 imgTemp = System.Drawing.Image.FromFile(strFilename, True)  
 Pedit.Image = New System.Drawing.Bitmap(imgTemp)  
 imgTemp.Dispose()  
 Pedit.Image.Save(strFilename)

which is better since the Image object cannot have its Save method called after the FileStream has been closed.

Chocol8
Your solution is better than mine.
Konrad Rudolph
I believe the opposite. Please take a look at the update.
Chocol8