-1

I have to delete root directory but some files open then it gives error "the process cannot access the file because it is being used by another process".

So, how to delete the directory when some files in open mode (I know using for each loop single file delete when it's open mode but I have to delete directory without for each loop.)

Hemang A
  • 1,012
  • 1
  • 5
  • 16

2 Answers2

2

You can't (at least not without closing those files).

The problem doesn't lie with your C# program, but with a severe limitation of the Windows kernel: It simply can't delete open (or locked) files (and thus not the directory, as it is now not empty).

You have two options:

  • Use a mechanism such as unlocker to forcibly close the files, then delete them
  • Have the application that opened the files close them, then delete

EDIT

Since you commented to add the information that the file is opened by your own application, things get easier:

  • Close the file inside your application
  • Run garbage collection to make sure your file handle is invalidated
  • Deletion should now work
Eugen Rieck
  • 64,175
  • 10
  • 70
  • 92
0

I have found a solution whenever some files have been open and do delete directory then it's deleted but it gives throw an only error.So, Please use try catch block and ignore the error.

        try
        {
            Directory.Delete("path", true);
        }
        catch (IOException)
        {

        }

        finally
        {
            Directory.CreateDirectory("Path");
        }
Hemang A
  • 1,012
  • 1
  • 5
  • 16
  • This is essentially a no-op, if it contains an open file: The direcotry will not be recreated, but the old one still exists – Eugen Rieck Apr 03 '19 at 11:30
  • you can create more than one directory in inner directory. After the end of the directory and outer directory put your files and write down this code it's working. I have done in my code. – Hemang A Apr 03 '19 at 12:03
  • ... as long as there is no open file in it, which was the OQ – Eugen Rieck Apr 03 '19 at 13:21