Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/36.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在创建新图像之前删除现有图像_C#_Asp.net_Image_Bitmap - Fatal编程技术网

C# 在创建新图像之前删除现有图像

C# 在创建新图像之前删除现有图像,c#,asp.net,image,bitmap,C#,Asp.net,Image,Bitmap,嗨,我有以下功能: private void CreateRoomImage(string path) { Directory.CreateDirectory(path); var file = ""; foreach (PanelView panelView in pv) { var RoomImage = GetRaumImageName(panelView.Title); file = path + GetImage

嗨,我有以下功能:

  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

这个问题有解决办法吗?如何删除现有映像?

似乎这可能是一种奇怪的竞争条件,其中file.exists尚未释放资源,并且正在尝试在释放之前删除。我可能会尝试类似的方法

    try
    {
        File.Delete(file);
    }
    catch
    {
       //File does not exist or another error occurred.
    }
我自己找到的

在PageLoad中,我也使用了thet“file”。我忘记处理图像:

 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();
    }

无论如何,谢谢你的帮助

为什么首先要删除文件?如果现有文件已经存在,您不能使其覆盖该文件吗


你可以做的另一件事是暂停线程大约400毫秒,直到操作系统完成它的工作,文件被完全删除,所有流被关闭。

GetRaumImage中的代码是什么??在这一行:file=path+GetImageFile(RoomImage);什么是“RoomImage”?我看不到任何声明…这只是意味着不会出现错误,也不意味着文件将被删除…这就是为什么您发布所有内容,而不仅仅是片段-我们没有机会诊断您的问题,因为问题出现在您没有向我们展示的代码中。