0

嗨,我有以下功能:

  private void CreateRoomImage(string path)
{
    Directory.CreateDirectory(path);
    var file = "";



    foreach (PanelView panelView in pv)
    {
        var RoomImage = GetRaumImageName(panelView.Title);
        file = path + GetImageFile(RoomImage);

        if (File.Exists(file))
        {
            File.Delete(file);
        }

        using (var img = GetRaumImage(panelView.Title, panelView))
        {

            ImageWriter imgWriter = new ImageWriter(ImageFormat.Bmp);
            imgWriter.Save(img, file);

        }



    }

}

我的问题是,每次我尝试删除现有文件时,我的程序都会抛出异常:

The process can not access the file because it is being used by another process

这个问题有解决方案吗?如何删除现有图像?

4

3 回答 3

0

It seems like this could be a weird race condition where the file.exists hasn't released the resource and it is trying to delete prior to release. I would probably try something along these lines.

    try
    {
        File.Delete(file);
    }
    catch
    {
       //File does not exist or another error occurred.
    }
于 2013-02-12T12:39:06.450 回答
0

我自己找到的。

在 PageLoad 我也使用“文件”。我忘了处理图像:

 foreach (PanelView panel in pv)
    {

        path = Request.PhysicalPath.Substring(0, Request.PhysicalPath.LastIndexOf('\\') + 1) + subPath + "\\" + GetRaumImageName(panel.Title);
        bitMap = new Bitmap(path + ".bmp");

        b0 = BmpToMonochromConverter.CopyToBpp(bitMap, 1);

       // bounce.updateInterface.UpdateProductImage(b0, panel.Panel.PRODUCT_ID, "", ref update_Handle);
        bitMap.Dispose();
    }

无论如何感谢您的帮助!

于 2013-02-12T12:45:47.033 回答
0

为什么首先要删除文件?如果它已经存在,你不能让它覆盖现有文件吗?

您可以做的另一件事是将线程暂停 400 毫秒,直到操作系统执行此操作并且文件被完全删除并且所有流都关闭。

于 2013-02-12T13:40:24.163 回答