In my WebApi
action method, I want to create/over-write a folder using this code:
string myDir = "...";
if(Directory.Exists(myDir))
{
Directory.Delete(myDir, true);
}
Directory.CreateDirectory(myDir);
// 1 - Check the dir
Debug.WriteLine("Double check if the Dir is created: " + Directory.Exists(myDir));
// Some other stuff here...
// 2 - Check the dir again
Debug.WriteLine("Check again if the Dir still exists: " + Directory.Exists(myDir));
Issue
Strangely, sometimes right after creating the directory, the directory does not exist!
Sometimes when checking the dir for the first time (where the number 1 is); Directory.Exist()
returns true
, other times false
. Same happens when checking the dir for the second time (where the number 2 is).
Notes
- None of this part of code throw any exception.
- Only can reproduce this when publishing the website on server. (Windows server 2008)
- Happens when accessing the same folder.
Questions
- Is this a concurrency issue race condition?
- Doesn't
WebApi
or the Operating System handle the concurrency? - Is this the correct way to overwrite a folder?
- Should I lock files manually when we have many API requests to the same file?
Or in General:
- What's the reason for this strange behavior?
UPDATE:
Using
DirectoryInfo
andRefresh()
instead ofDirectory
does not solve the problem.Only happens when the recursive option of Delete is
true
. (and the directory is not empty).