Access is Denied When Renaming Folder

My approach to solving this problem is to run the utility Handle, by Mark Russinovich of Windows Sysinternals. You can find it here.

This utility will show all the open handles on the system and which process is using them. One of them may have a path to the folder you are trying to rename.

I typically redirect the output of handle.exe to a file.

handle >handles.txt

Then I look at handles.txt in a text editor and search for the name of the folder I was trying to rename. It will appear in a section of handles belonging to the process that is keeping the handle to that folder open, and hence preventing it from being renamed. It shows the pid of the offending process, which you can decide how to deal with, in case you need to terminate it.

e.g. Trying to rename myfolder I forgot I had started a service running using pm2 (a process monitor) The output of Handle.exe included the following:

node.exe pid: 12752 DISCO\Stu
   40: File  (---)   C:\Dev\myfolder\service

I fixed this by disabling Quick Access:

See Screenshot:

[]


The answer is quite simple:

Windows does not permit deletion or renaming a directory/folder which is

  • the current directory of any running process (application/service) like the command process, or
  • any subdirectory of the directory to rename is the current directory of any running process, or
  • any file is opened in the directory to rename or any of its subdirectories by any process with OF_SHARE_DENY_READ, OF_SHARE_DENY_WRITE, OF_SHARE_EXCLUSIVE used on opening the file.

In other words as long as the directory itself or any file or subdirectory in this directory or its subdirectories is in use by any application, Windows denies renaming or deleting the directory.

On Unix/Linux it is possible to delete or rename a directory while it is in use by 1 or more running processes. The running *nix process has to handle the special use case that the directory or file just accessed successfully a millisecond before does suddenly not exist anymore.