none
File in use when no program is using it. RRS feed

  • Question

  • I am trying to get the user to select a image from a folder, and then be able to clear all files in that folder the file resides in. I get the error System.IO.IOException: 'The process cannot access the file '0001.png' because it is being used by another process.' My program doesn't even open the file, and if it does it removes it from the viewing picturebox. Code:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using System.Configuration;
    using System.Diagnostics;
    using System.IO;
    namespace DiscordCacheReader
    {
        public partial class Form1 : Form
        {
            Image file;
            public Form1()
            {
    
    
                InitializeComponent();
                pictureBox1.SizeMode = PictureBoxSizeMode.CenterImage;
                pictureBox1.ImageLocation = @"https://proxy.duckduckgo.com/iu/?u=http%3A%2F%2Fmaestroselectronics.com%2Fwp-content%2Fuploads%2F2017%2F12%2FNo_Image_Available.jpg&f=1";
            }
    
            private void label1_Click(object sender, EventArgs e)
            {
    
            }
    
            private void pictureBox1_Click(object sender, EventArgs e)
            {
    
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                if (textBox1.Text.Length == 0)
                {
                    MessageBox.Show("Error! Please provide a path", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    pictureBox1.ImageLocation = @textBox1.Text;
                    pictureBox1.SizeMode = PictureBoxSizeMode.CenterImage;
                    button3.Visible = true;
                }
    
            }
    
            private void button2_Click(object sender, EventArgs e)
            {
                OpenFileDialog choofdlog = new OpenFileDialog();
                choofdlog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\discord\Cache";
                choofdlog.Filter = "File (*.*)|*.*";
                choofdlog.FilterIndex = 1;
                choofdlog.Multiselect = false;
    
    
                if (choofdlog.ShowDialog() == DialogResult.OK)
                {
                    var sFileName = choofdlog.FileName;
                    textBox1.Text = sFileName;
                    file = Image.FromFile(choofdlog.FileName);
                    button1.Visible = true;
                }
            }
    
            private void textBox1_TextChanged(object sender, EventArgs e)
            {
    
            }
    
            private void button3_Click(object sender, EventArgs e)
            {
                SaveFileDialog f = new SaveFileDialog();
                f.Filter = "PNG (*.png)|*.png";
                f.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                if (f.ShowDialog() == DialogResult.OK)
                {
    
                    file.Save(f.FileName);
                }
            }
    
            private void button4_Click(object sender, EventArgs e)
            {
                if (Process.GetProcessesByName("discord").Length > 0)
                {
                    DialogResult d1 = MessageBox.Show("Error! Discord is running! Click retry to close discord and retry!", "Error!", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error);
    
                    if (d1 == DialogResult.Retry)
                    {
                        Process[] localByName = Process.GetProcessesByName("discord");
                        foreach (Process p in localByName)
                        {
                            p.Kill();
                        }
    
                        button4_Click(sender, e);
                    }
                }
                else
                {
                    if (textBox1.Text.Length != 0)
                    {
                        pictureBox1.ImageLocation = @"https://proxy.duckduckgo.com/iu/?u=http%3A%2F%2Fmaestroselectronics.com%2Fwp-content%2Fuploads%2F2017%2F12%2FNo_Image_Available.jpg&f=1";
                        string parent = System.IO.Directory.GetParent(@textBox1.Text).FullName;
                        
                        int fileCount = Directory.GetFiles(parent).Length;
                        DialogResult d2 = MessageBox.Show("Discord is closed! Are you sure you want to clear your cached folder? This will delete " + fileCount + @" file(s) and may not be recoverable!", "Info!", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                        if (d2 == DialogResult.No)
                        {
                            MessageBox.Show("Canceled!", "Info!", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        else
                        {
                            pictureBox1.ImageLocation = @"https://proxy.duckduckgo.com/iu/?u=http%3A%2F%2Fmaestroselectronics.com%2Fwp-content%2Fuploads%2F2017%2F12%2FNo_Image_Available.jpg&f=1";
    
    
    
                            string epice = System.IO.Directory.GetParent(textBox1.Text).FullName;
                            System.IO.DirectoryInfo di = new DirectoryInfo(epice);
                            
                            foreach (FileInfo file in di.GetFiles())
                            {
                                
                                string finalpath = @di + "\\" + @file;
                                
                                MessageBox.Show(finalpath);
                                
                                using (StreamReader sr = new StreamReader(@finalpath))
                                {
                                    file.Delete();
                                }
                               
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show("Error! Please provide a path", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }
    }
    
    
    


    Griffin

    Thursday, February 28, 2019 2:12 AM

All replies

  • Hi Griffin,

    Thank you for posting here.

    According to your description, you want to solve the error ‘The process cannot access the file '0001.png' because it is being used by another process.'.

    I have reproduced your problem, you could try the following change.

    Change this in button4_Click

    using (StreamReader sr = new StreamReader(@finalpath))
    
                                {
    
                                    file.Delete();
    
                                }

    Into

    File.Delete(finalpath);

    Result:

    Hope my solution could be helpful.

    Best regards,

    Jack



    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.


    Thursday, February 28, 2019 5:12 AM
    Moderator
  • System.IO.IOException: 'The process cannot access the file 'C:\Users\USER\Desktop\test\0001.png' because it is being used by another process.' This is the new error I get. I have the image in the picturebox switch to the selected image when you click browse. When you press delete cache it changes the image to the default image so it wouldn't interfere. I have it switch then refresh to clear anything.

    Griffin

    Thursday, February 28, 2019 12:44 PM
  • You're using a lot of code to delete the files from a directory. You're enumerating the files using GetFiles and then opening each one using a stream. As Jack mentions the file is now locked by your process so you cannot delete it. `sr` has a lock on it. Just do this.

    foreach (var file in di.GetFiles())
       file.Delete();
    
    

    Get rid of all the other code in your foreach loop.

    You also mentioned a PictureBox, where is that coming in? If you attach an Image to a PictureBox then the Image has to remain valid until the PB is gone. Note that if you change the Image property of a PictureBox then the old Image is not automatically disposed. You have to do that yourself. If an Image is created using a Stream then the Stream has to remain open until the Image is disposed. So if you use a Stream to read an image file, then assign it to the PB and then change the image to something else the original image file is still open until the runtime eventually cleans up the Image which then cleans up the Stream.


    Michael Taylor http://www.michaeltaylorp3.net

    Thursday, February 28, 2019 3:56 PM
    Moderator
  • I came across this a couple of times and used Process Explorer resolve the issue.

    You can use Process Explorer https://docs.microsoft.com/en-us/sysinternals/downloads/process-explorer to ensure if any other process is accessing the file. If so you can terminate that process to release the file then you may try to delete it again using your application.

    More info is here https://www.techsupportalert.com/content/how-find-out-which-windows-process-using-file.htm

    Thanks

    Eswar

    Thursday, February 28, 2019 7:08 PM
  • Hi 

    Thanks for feedback.

    For your new error, you could try update the following code in your button3_click.

    Please pay attention to my bold code.

    Code:

    private void button3_Click(object sender, EventArgs e)
            {
                SaveFileDialog f = new SaveFileDialog();
                f.Filter = "PNG (*.png)|*.png";
                f.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                if (f.ShowDialog() == DialogResult.OK)
                {
                    file.Save(f.FileName);
                    file.Dispose();
                    file = null;
                }
            }
    

    Hope my modify could be helpful.

    Best Regards,

    Jack



    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, March 1, 2019 7:03 AM
    Moderator