The process cannot access the file because it is being used by another process.

I add images to the FlowLayoutPanel control using 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 images uploaded in 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?

+3
source share
3 answers

Image.FromFileactually locks the file that it downloads , and only releases the lock after it is placed.

The solution is to draw the image into a different graphic context of the image (thus effectively copying it) and delete the original image.

+5

! .

.

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: . , :)

 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)

, Image Save, FileStream.

+5

I found that this solution is best to unlock the image file after loading it into the PictureBox:

PictureBoxName.LOAD (image file name with full path)

0
source

Source: https://habr.com/ru/post/1771201/


All Articles