Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IOException ("file or directory already exists") while trying to create a directory

I have a strange problem in our C# project which occurs while trying to create a directory via IronPython script. This is the code:

targetTemplateDirectory = Path.Combine(Data, "Templates\\CheckedReports")

if not Directory.Exists(targetTemplateDirectory):
    Directory.CreateDirectory(targetTemplateDirectory)

The problem is an IOException telling me that it is not possible to create the folder "H:\ProductName\Data\Templates\CheckedReports" because a file or directory with the same name already exists.

According to MSDN the method Directory.CreateDirectory() does not throw any exception when the directory already exists.

I know that a file named "CheckedReports" can be the reason for this exception, but it is very, very unlikely that the customer has created that file manually. In addition to that there is no line of code which contains the word "CheckedReports" (besides the mentioned script). Moreover the application is used by a few thousand customers, the script executed on every machine and only one customer reported this issue.

Is there any possibility for this exception to occur other than a file with the same name? Maybe something related to permissions, removable media or network drives?

like image 354
Emmett Brown Avatar asked Jan 09 '13 13:01

Emmett Brown


2 Answers

Although it would be a bit of an overkill to have this only for one user, it should be possible to check if a file with that name exists.

FileInfo myFile = new FileInfo(targetTemplateDirectory);
if (myFile.Exists)
    myFile.Delete();

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

Probably this would solve the issue IF ofcourse the I/O exception was caused by a file having the same name. If it would be caused by the user because the "network name is not known", then I would not have a clue either.

like image 92
CuccoChaser Avatar answered Oct 18 '22 02:10

CuccoChaser


We had the same, and in our case it was pretty clear it was a permissions issue. We were expecting the documented UnauthorizedAccessException, but that's not what we got.

In the stack we have Directory.CreateDirectory calling Directory.InternalCreateDirectory.

Inside it there is this note:

        //Note that InternalExists may fail due 
        // to Win32 ACL's preventing us from seeing a directory, and this
        // isn't threadsafe. 

There are more notes about it, that go deeper into that fact, the code may try to create the directory that's already there when it couldn't see it.

like image 3
eglasius Avatar answered Oct 18 '22 04:10

eglasius