删除图片框中显示的文件

时间:2013-08-02 05:21:43

标签: c# asp.net

当我点击delete按钮时,我从openfiledialoge中选择文件并将其显示在图片框中并在文本框中显示我的异常The process cannot access the file because it is being used by another process.  我搜索了很多这个例外以获得解决,但是当我尝试使用imagename关闭文件时,我尝试关闭文件,即我在图片框中显示的文件;使用IsFileLocked方法,这将关闭并删除特定目录路径的所有文件,但如何删除picturebox中显示的唯一文件,我出错了

     public partial class RemoveAds : Form
    {
        OpenFileDialog ofd = null;
        string path = @"C:\Users\Monika\Documents\Visual Studio 2010\Projects\OnlineExam\OnlineExam\Image\"; // this is the path that you are checking.

        public RemoveAds()
        {
            InitializeComponent();
        }


        private void button1_Click(object sender, EventArgs e)
        {
            if (System.IO.Directory.Exists(path))
            {
                 ofd = new OpenFileDialog();
                ofd.InitialDirectory = path;
                DialogResult dr = new DialogResult();
                if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    Image img = new Bitmap(ofd.FileName);
                    string imgName = ofd.SafeFileName;
                    txtImageName.Text = imgName;
                    pictureBox1.Image = img.GetThumbnailImage(350, 350, null, new IntPtr());
                    ofd.RestoreDirectory = true;
                }
            }
            else
            {
                return;
            } 
        }
private void button2_Click(object sender, EventArgs e)
        {
            //Image img = new Bitmap(ofd.FileName);
            string imgName = ofd.SafeFileName;  
             if (Directory.Exists(path))
             {

                 var directory = new DirectoryInfo(path);
                 foreach (FileInfo file in directory.GetFiles())
                 { if(!IsFileLocked(file))
                     file.Delete(); 
                 }
             }


        }
        public static Boolean IsFileLocked(FileInfo path)
        {
            FileStream stream = null;   
            try
            { //Don't change FileAccess to ReadWrite,
                //because if a file is in readOnly, it fails.
                stream = path.Open ( FileMode.Open, FileAccess.Read, FileShare.None ); 
            } 
            catch (IOException) 
            { //the file is unavailable because it is:
                //still being written to or being processed by another thread
                //or does not exist (has already been processed)
                return true;
            } 
            finally
            { 
                if (stream != null)
                    stream.Close();
            }   
            //file is not locked
            return false;
        }
    }

提前感谢您提供任何帮助

5 个答案:

答案 0 :(得分:5)

此问题的(先前)接受的答案是非常糟糕的做法。如果你在System.Drawing.Bitmapread the documentation,特别是对于从文件创建位图的重载,你会发现:

  

文件保持锁定状态,直到处理了位图。

在您的代码中创建位图并将其存储在本地变量中,但是在完成后您永远不会将其丢弃。这意味着您的图像对象已超出范围,但尚未对您尝试删除的图像文件释放锁定。对于实现IDisposable的所有对象(如Bitmap),您必须自己处理它们。例如,请参阅this question(或搜索其他人 - 这是一个非常重要的概念!)。

要正确纠正问题,您只需在完成后处理图像:

 if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
 {
      Image img = new Bitmap(ofd.FileName);  // create the bitmap
      string imgName = ofd.SafeFileName;
      txtImageName.Text = imgName;
      pictureBox1.Image = img.GetThumbnailImage(350, 350, null, new IntPtr());
      ofd.RestoreDirectory = true;
      img.Dispose();  // dispose the bitmap object
 }

请不要接受以下答案中的建议 - 您几乎不需要致电GC.Collect,如果您需要这样做以使事情有效,那么这应该是一个非常强烈的信号,表明您正在做其他事情错误。

另外,如果你只想删除一个文件(你显示的位图),你的删除代码是错误的,并且会删除目录中的每个文件(这只是重复Adel的观点) )。此外,为了存储文件名而不是保持全局OpenFileDialog对象存活,我建议摆脱它并仅保存文件信息:

FileInfo imageFileinfo;           //add this
//OpenFileDialog ofd = null;      Get rid of this

private void button1_Click(object sender, EventArgs e)
{
     if (System.IO.Directory.Exists(path))
     {
         OpenFileDialog ofd = new OpenFileDialog();  //make ofd local
         ofd.InitialDirectory = path;
         DialogResult dr = new DialogResult();
         if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
         {
              Image img = new Bitmap(ofd.FileName);
              imageFileinfo = new FileInfo(ofd.FileName);  // save the file name
              string imgName = ofd.SafeFileName;
              txtImageName.Text = imgName;
              pictureBox1.Image = img.GetThumbnailImage(350, 350, null, new IntPtr());
              ofd.RestoreDirectory = true;
              img.Dispose();
         }
         ofd.Dispose();  //don't forget to dispose it!
     }
     else
     {
         return;
     }
 }

然后在第二个按钮处理程序中,您可以删除您感兴趣的文件。

        private void button2_Click(object sender, EventArgs e)
        {                
           if (!IsFileLocked(imageFileinfo))
            {                 
                imageFileinfo.Delete();
            }
        }

答案 1 :(得分:0)

使用此代码

string imgName = ofd.SafeFileName;
            if (Directory.Exists(path))
            {

                var directory = new DirectoryInfo(path);
                foreach (FileInfo file in directory.GetFiles())
                {
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                        file.Delete();
                }
            }

答案 2 :(得分:0)

你的button2_Click事件处理程序正在遍历目录中的所有文件&做删除。

您需要更改以下代码:

 public partial class RemoveAds : Form
{
    OpenFileDialog ofd = null;
    string path = @"C:\Users\Monika\Documents\Visual Studio 2010\Projects\OnlineExam\OnlineExam\Image\"; // this is the path that you are checking.
    string fullFilePath;

    public RemoveAds()
    {
        InitializeComponent();
    }


    private void button1_Click(object sender, EventArgs e)
    {
        if (System.IO.Directory.Exists(path))
        {
             ofd = new OpenFileDialog();
            ofd.InitialDirectory = path;
            DialogResult dr = new DialogResult();
            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                Image img = new Bitmap(ofd.FileName);
                string imgName = ofd.SafeFileName;
                txtImageName.Text = imgName;
                pictureBox1.Image = img.GetThumbnailImage(350, 350, null, new IntPtr());
                fullFilePath = ofd.FilePath;
                ofd.RestoreDirectory = true;
            }
        }
        else
        {
            return;
        } 
    }

    private void button2_Click(object sender, EventArgs e)
        {
             FileInfo file = new FileInfo(fullFilePath);

             if(!IsFileLocked(file))
                 file.Delete(); 
         }


    }

    public static Boolean IsFileLocked(FileInfo path)
    {
        FileStream stream = null;   
        try
        { //Don't change FileAccess to ReadWrite,
            //because if a file is in readOnly, it fails.
            stream = path.Open ( FileMode.Open, FileAccess.Read, FileShare.None ); 
        } 
        catch (IOException) 
        { //the file is unavailable because it is:
            //still being written to or being processed by another thread
            //or does not exist (has already been processed)
            return true;
        } 
        finally
        { 
            if (stream != null)
                stream.Close();
        }   
        //file is not locked
        return false;
    }
}

答案 3 :(得分:0)

通过使用GetThumnailImage,您必须指定静态的宽度和高度。 请改用Load方法。 例如:pictureBox1.Load(图像的路径);使用此功能,在关闭应用程序之前删除图像或文件夹没有任何问题。不需要创建其他方法。 希望这有帮助

答案 4 :(得分:0)

我遇到了同样的问题:我在 PictureBox 中加载了一个文件,当我尝试删除它时,我得到了同样的例外。
仅在显示图像时才会发生这种情况 我尝试了所有这些:

picSelectedPicture.Image.Dispose();
picSelectedPicture.Image = null;
picSelectedPicture.ImageLocation = null;  

仍然有同样的例外。
然后我在CodeProject上找到了这个:[c#] delete image which is opened in picturebox 它不是使用PictureBox.Load(),而是从文件中创建Image并将其设置为PictureBox.Image

...
// Create image from file and display it in the PictureBox
Image image = GetCopyImage(imagePath);
picSelectedPicture.Image = image;
...  

private Image GetCopyImage(string path) {
    using (Image image = Image.FromFile(path)) {
        Bitmap bitmap = new Bitmap(image);
        return bitmap;
    }
}  

删除文件时不再有例外。
恕我直言,这是最合适的解决方案。

修改
我忘了提到你可以在显示后立即安全地删除文件:

...
// Create image from file and display it in the PictureBox
Image image = GetCopyImage(imagePath);
picSelectedPicture.Image = image;
System.IO.File.Delete(imagePath);
...