There are a number of possibilities as to why folders cannot be deleted but this one I came across recently got my attention. While decompressing a zip file it created its extracted folder but when I came to remove the folder it came up with the error “Cannot delete file: Cannot read from the source file or disk”. After investigating I realised that it had a trailing space at the end of the folder. Now I knew what was causing the removal to fail but how to get rid of it?
Well there are a few ways on how to remove folders with trailing spaces:
1. Using the “\\?\” syntax
2. Using 8.3 short filename format (if folder is more than 8 characters)
Below is an example code which creates a folder called “testfolder” in C:\TEMP with a trailing space. Note that after the space \\ is required for it to create the space after the folder. Once compiled and run it will create the testfolder, pause for 5 seconds and then remove it. The trailing space can be more than just one space character.
#include <stdio.h>
#include <windows.h>
int main()
{
CreateDirectory(“C:\\TEMP\\testfolder \\”, NULL);
Sleep(5000);
RemoveDirectory(“C:\\TEMP\\testfolder \\”);
return 0;
}
Examples on how to delete trailing space folders from the console.
C:\>rd c:\temp\testfo~1
C:\>rd “\\?\c:\temp\testfolder ”
Reference:
Thank you for this! I was really scratching my head. My folder was 6 characters long, so I couldn’t use the 8.3 trick, but the //?/ trick worked perfectly. What exactly is that syntax? Somehow never run across it before.
Glad I could help, because of the trailing space certain Windows API’s reading it as ANSI fails to delete. Adding \\?\ tells it is in UNICODE even though it really isn’t but then the Unicode API’s can delete it as it can take in the trailing space :-). Here is a good article with some useful info
http://msdn.microsoft.com/en-gb/library/windows/desktop/aa365247(v=vs.85).aspx
Excellent tip! \\?\ worked great!
It didn’t work for me 🙁
But I managed to remove the trailing space using WinRAR and it worked!