Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why wouldn't a folder exist after you create it?

Tags:

c#

This doesn't seem to make sense, so I'm obviously doing something wrong:

DirectoryInfo folder = new DirectoryInfo(Environment.CurrentDirectory + @"\Test");

if (folder.Exists == false) {
    folder.Create();

    var doesItExists = folder.Exists;
}

Creates a folder if it doesn't exist. Except doesItExists is always false. Why would it be false if I just created it?

like image 405
sircodesalot Avatar asked Jul 24 '13 16:07

sircodesalot


People also ask

Does mkdir overwrite existing directory in Java?

mkdir WILL give you an error if the directory already exists. mkdir -p WILL NOT give you an error if the directory already exists. Also, the directory will remain untouched i.e. the contents are preserved as they were.

How do you check if a folder exists in JS?

const fs = require("fs") fs. access("./directory-name", function(error) { if (error) { console. log("Directory does not exist.") } else { console. log("Directory exists.") } })

How do you create a folder if it doesn't exist in Java?

createDirectories() creates a new directory and parent directories that do not exist. This method does not throw an exception if the directory already exists. What happens if permission is required to create ? For Android It only works on API 26 and up so Make sure to check this line if (Build.


3 Answers

The value in folder.Exists is cached. I would suggest doing this check:

var doesItExists = Directory.Exists(folder.FullName);

Or you could call folder.Refresh() to update the cache before checking if the directory exists after creating it. See this previous answer.

like image 116
David Sherret Avatar answered Nov 15 '22 17:11

David Sherret


Assuming that folder is a DirectoryInfo or FileSystemInfo, it reads its values once, and then returns cached values. It doesn't notice that you've created the directory. Call Refresh().

Alternatively use Directory.Exists().

like image 21
Roger Lipscombe Avatar answered Nov 15 '22 18:11

Roger Lipscombe


this will get you true,you need to call refresh():

            DirectoryInfo folder = new DirectoryInfo(Environment.CurrentDirectory + @"\Test");

            if (folder.Exists == false)
            {
                folder.Create();
                folder.Refresh();

                var doesItExists = folder.Exists;
            }
like image 26
terrybozzio Avatar answered Nov 15 '22 17:11

terrybozzio