简体   繁体   中英

Is there any point in checking if a directory exists before creating it in C#?

When I want to do anything that involves reading and writing to directories I have always been in the habit of checking to see if a directory exists and if it doesn't I will create it. Is there any point in doing this? If i run the following code i get no exception. Creating a directory that already exists does nothing bad.

Directory.CreateDirectory("C:\\test");
Directory.CreateDirectory("C:\\test");

To me checking first seems like a waste of resources. If the directory doesnt exist, then 2 commands need to be executed. I would imagine that CreateDirectory performs a check before doing anything, so it would most definitely be redundant to do this if this is the case.

So to pitch the question. When creating directories, should i do the following or can i ditch the if statement?

if(Directory.Exists("C:\\test")) Directory.CreateDirectory("C:\\test");

Note - I am aware that the performance benefit here is incredibly tiny, I am more interested in keeping code tidy and ditching lines i dont need.

It is not created if it allready exists according to msdn

Any and all directories specified in path are created, unless they already exist or unless some part of path is invalid. If the directory already exists, this method does not create a new directory, but it returns a DirectoryInfo object for the existing directory.

You can also check the source here and see that a check if the directory exists is performed.

Directory.CreateDirectory :

Creates all directories and subdirectories in the specified path unless they already exist.

If your intent is to either create new or use existing directory, then you don't need to check for existence.

Moreover, reading about Directory.Exists :

The Exists method returns false if any error occurs while trying to determine if the specified file exists

Exists can't be used to know for sure if CreateDirectory will sucess, so you are right, it doesn't make sense. Any exception (eg invalid name) will still be thrown during CreateDirectory .

It only make sense if you have to do something when directory is existing already, eg close opened file located in this directory or add this info into log.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM