Search code examples
c#openfiledialog

OpenFile Dialog Box keeps resources open


After opening a photo in my application using the Openfile Dialog I cannot do anything with the file unless I close my application. I have placed the OpenFile Dialog in a using statement and tried various ways to release resources with no success. How can I release the process to avoid the error message "The process cannot access the file because it is being used by another process?

       using (OpenFileDialog GetPhoto = new OpenFileDialog())
        {
            GetPhoto.Filter = "images | *.jpg";
            if (GetPhoto.ShowDialog() == DialogResult.OK)
            {
                pbPhoto.Image = Image.FromFile(GetPhoto.FileName);
                txtPath.Text = GetPhoto.FileName;
                txtTitle.Text = System.IO.Path.GetFileNameWithoutExtension(GetPhoto.Fi‌​leName);
                //GetPhoto.Dispose();  Tried this
                //GetPhoto.Reset();  Tried this
                //GC.Collect(): Tried this
            }
        }

Solution

  • Your problem is not (OpenFileDialog) your problem is for PictureBox
    you can use this for load image or if this not works do this for load image

            OpenFileDialog GetPhoto = new OpenFileDialog();
            GetPhoto.Filter = "images | *.jpg";
            if (GetPhoto.ShowDialog() == DialogResult.OK)
            {
                FileStream fs = new FileStream(path: GetPhoto.FileName,mode: FileMode.Open);
                Bitmap bitmap = new Bitmap(fs);
                fs.Close(); // End using
                fs.Dispose();
                pbPhoto.Image = bitmap;
                txtPath.Text = GetPhoto.FileName;
                txtTitle.Text = System.IO.Path.GetFileNameWithoutExtension(GetPhoto.Fi‌​leName);
            }