0

I have created a button. In the event handler for the button I want to delete all the files in the folder (abc).

Here is the code for this:

    private void button1_Click_1(object sender, EventArgs e)
    {
        MessageBox.Show("Are you sure!!!! The files in the folder will be deleted permanently");
        this.Close();
        string[] filePaths = Directory.GetFiles(@"C:\abc\");
        foreach (string filePath in filePaths)
            File.Delete(filePath);
    }

For example, there is a Word file in the folder and if it is opened I get a error message:

The process cannot access the file 'C:\abc\New Microsoft Word Document.docx' because it is being used by another process.

Tetsujin no Oni
  • 7,300
  • 2
  • 29
  • 46
  • http://stackoverflow.com/questions/317071/how-do-i-find-out-which-process-is-locking-a-file-using-net there are samples to find process holding the lock. – gp. Oct 06 '13 at 04:09
  • @gp. this is the original thread: http://stackoverflow.com/questions/876473/is-there-a-way-to-check-if-a-file-is-in-use/11060322#11060322 – Jeremy Thompson Oct 06 '13 at 05:56

1 Answers1

1

You can use Process class to find that process, forcibly close that program and then delete that file. Something like this...

Process [] proc Process.GetProcessesByName("winword");
proc[0].Kill();

However I wouldn't suggest this because windows also do not delete opened files.

Jeremy Thompson
  • 61,933
  • 36
  • 195
  • 321
Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208