Directory.Exists reasonable for time?

My application has the following code snippet:

if (!Directory.Exists(myPath)) Directory.CreateDirectory(myPath); 

If I run it in a regular unit test, it sometimes passes, sometimes not. There is always a catalog (I was convinced of this, so technically it will never be "created" by code). But each time Directory.Exists(myPath) returned false , which causes the code to try to create a folder, and then I get a UnauthorizedAccessException !

The funny thing is, if I put a breakpoint on CreateDirectory and then move the yellow up arrow to check, the test returns true !

What's happening?

myPath is \\nameOfLocalMachine\sharedFolder . The share is reliable and constantly used .... NET 4.0

I just created a violinist that mimics 3,000 sequence requests. 175 failed ... All with the same message:

Access to path '\ nameOfLocalMachine \ sharedFolder \ randomFileName.json' denied

+2
source share
1 answer

This error is very common for Windows. Programs open a descriptor in a directory like this and determine file sharing. This allows someone to delete the directory, even if the program uses it. The directory will not virtually disappear from the file system until this handle is closed. It follows that an attempt to recreate this directory may not work; it still exists. Windows generates a "denied access" error reported in your C # program using UnauthorizedAccessException.

Although this sounds like an obscure feature, every Windows program does it. Each process has a default working directory, the value Environment.CurrentDirectory. Creating a descriptor in such a directory ensures that it cannot disappear while using the program. There are other cases, for example, FileSystemWatcher. Or the program is busy iterating the directory. Antivirus programs and search indexes are notorious for making it difficult to diagnose the sources of such errors.

Otherwise, this is a standard hazard for a multitasking operating system. You are not the only one using the file system. Not re-deleting and creating the same directory should be very high on your list. If absolutely necessary, rename the directory before deleting it. You still will not be able to delete the renamed directory, but you will not be able to recreate it. You can delete it later, the next time you need to do it. Then there is much less chance of trouble. Because more time has passed.

+3
source

Source: https://habr.com/ru/post/1303406/


All Articles