该进程无法访问该文件,因为该文件正由另一个进程使用

时间:2010-10-24 19:31:58

标签: vb.net exception file-io delete-file

我通过以下代码将图像添加到FlowLayoutPanel控件

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 process cannot access the file xxxx because it is being used by another process.

                    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

那我在这里做错了什么?

3 个答案:

答案 0 :(得分:5)

Image.FromFile actually locks the file it loads并且只有在处理完锁后才会释放锁。

解决方案是将图像绘制到另一个图像的图形上下文中(从而有效地复制它)并处理原始图像。

答案 1 :(得分: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() 

<强>更新 这是康拉德所建议的。对于那里的所有新手,就像我一样:)

 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)

这是更好的,因为在FileStream关闭后,Image对象无法调用其Save方法。

答案 2 :(得分:0)

我发现这个解决方案是最好在将图像文件加载到PictureBox后解锁图像文件:

PictureBoxName .LOAD(带完整路径的图片文件名