Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting File which is displayed in picturebox

Tags:

c#

asp.net

I am selecting file from openfiledialoge and displaying it in picturebox and its name in textbox when I click on delete button I am getting exception The process cannot access the file because it is being used by another process. I searched a lot for this exception to get resolved but i didn't fine any of them working, when i tried closing file with imagename which is in textbox i.e the file i am displaying in picturebox ; using IsFileLocked method,this closes and deletes all files of particular directory path ,but how can I delete the only file shown in picturebox,where I am going wrong

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

Thanks in advance for any help

like image 610
Durga Avatar asked Aug 02 '13 05:08

Durga


2 Answers

The (previously) accepted answer to this question is very poor practice. If you read the documentation on System.Drawing.Bitmap, in particular for the overload that creates a bitmap from a file, you will find :

The file remains locked until the Bitmap is disposed.

in your code you create the bitmap and store it in a local variable but you never dispose of it when you are done. This means your image object has gone out of scope but has not released its lock on the image file you are trying to delete. For all objects that implement IDisposable (like Bitmap) you must dispose of them yourself. See this question for example (or search for others - this is a very important concept!).

To correct the problem properly you simply need to dispose of the image when you are done with it :

 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
 }

Please do not take the advice in the answer below - you should nearly never need to call GC.Collect and if you need to do it to make things work it should be a very strong signal that you are doing something else wrong.

Also, if you only want to delete the one file (the bitmap you have displayed) your deletion code is wrong and will delete every file in the directory as well (this is just repeating Adel's point). Further, rather than keep a global OpenFileDialog object alive simply to store the file name, I would suggest getting rid of that and saving just the file info :

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

Then in your second button handler you can just delete the one file you are interested in.

        private void button2_Click(object sender, EventArgs e)
        {                
           if (!IsFileLocked(imageFileinfo))
            {                 
                imageFileinfo.Delete();
            }
        }
like image 177
J... Avatar answered Oct 12 '22 00:10

J...


I had the same problem : I loaded a file in a PictureBox and when trying to delete it I got the same exception.
This occurred only when the image was displayed.
I tried them all :

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

and still got the same exception.
Then I found this on CodeProject : [c#] delete image which is opened in picturebox.
Instead of using PictureBox.Load() it creates an Image from the file and sets it as 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;
    }
}  

No more exceptions when I delete the file.
IMHO, this is the most suitable solution.

EDIT
I forgot to mention that you can safely delete the file immediately after display :

...
// Create image from file and display it in the PictureBox
Image image = GetCopyImage(imagePath);
picSelectedPicture.Image = image;
System.IO.File.Delete(imagePath);
...  
like image 36
Jack Griffin Avatar answered Oct 12 '22 02:10

Jack Griffin