Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Directory.CreateDirectory does not always create the folder

I have created a folder on the path C:\Users\MYUSER\Desktop\TEST\.

I have the following code:

private const string DIR = @"C:\Users\MYUSER\Desktop\TEST\tmp";

static void Main(string[] args)
{
    if (Directory.Exists(DIR))
        Directory.Delete(DIR);

    for (int i = 0; i < 100; i++)
    {
        var dinfo = Directory.CreateDirectory(DIR);
        Directory.Delete(DIR);
    }

    Directory.CreateDirectory(DIR);
}

When I execute the code, most times it runs OK, and I can see that there is a folder tmp inside the folder TEST.

My issue is that some other times, Directory.CreateDirectory(DIR) does not create a directory at all. I even checked the DirectoryInfo it returns and its Exists property is false and Directory.CreateDirectory(DIR) will not work because the folder does not exist. Is there any explanation for this weird behavior?

like image 781
Bsa0 Avatar asked Aug 27 '15 19:08

Bsa0


People also ask

Why does mkdir not create directory?

mkdir: cannot create directory – Permission denied The reason for this error is that the user you're running the mkdir as, doesn't have permissions to create new directory in the location you specified. You should use ls command on the higher level directory to confirm permissions.

How to Create folder if not exist in c#?

For creating a directory, we must first import the System.IO namespace in C#. The namespace is a library that allows you to access static methods for creating, copying, moving, and deleting directories.

Does Python create folder if not exists?

To create a directory if not exist in Python, check if it already exists using the os. path. exists() method, and then you can create it using the os. makedirs() method.


1 Answers

Had the same problem. No errors occurred, but folders simply would not be created. Just discovered the root of the issue and the easy fix.

I had something like:

Directory.CreateDirectory("/Users/MyAccount/NewFolder");
#Some code...
Directory.CreateDirectory("/Users/MyAccount/NewFolder/SubFolder");

This would fail to create folders under directories that were created before it.

Solution: Add a slash at the end of the path.

Instead of:

Directory.CreateDirectory("/Users/MyAccount/NewFolder/SubFolder");

Do:

Directory.CreateDirectory("/Users/MyAccount/NewFolder/SubFolder/");

Adding the trailing slash fixed the issue, and it now creates the folder 100% of the time. No more problems.

like image 96
Asyranok Avatar answered Oct 07 '22 03:10

Asyranok