Deleting File which is displayed in picturebox

前端 未结 5 1221
北海茫月
北海茫月 2021-01-17 15:39

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

相关标签:
5条回答
  • 2021-01-17 15:57

    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();
                }
            }
    
    0 讨论(0)
  • 2021-01-17 16:06

    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);
    ...  
    
    0 讨论(0)
  • 2021-01-17 16:07

    By using GetThumnailImage you have to specify the width and height which is static. Use the Load method instead. eg: pictureBox1.Load(Path to the image); by using this u will have no problem in deleting the image or the folder before closing the app. no other methods need to be created. hope this helps

    0 讨论(0)
  • 2021-01-17 16:12

    Your button2_Click event handler is cycling through all the files inside your directory & doing the deletes.

    You need to change your code like the following:

     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;
        }
    }
    
    0 讨论(0)
  • 2021-01-17 16:18

    use this code

    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();
                    }
                }
    
    0 讨论(0)
提交回复
热议问题