Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to check if directory/file exist or not?

Tags:

c#

file

directory

Which one code is better?

Code1:

if (!Directory.Exists("DirectoryPathHere"))
    Directory.CreateDirectory("DirectoryPathHere");

Code2:

Directory.CreateDirectory("DirectoryPathHere");

I think Code2 because as I saw it not gives any error and its not making new folder when the folder already exists, so I though that checking for folder existence is useless. Right?

like image 402
biox Avatar asked Feb 15 '23 14:02

biox


2 Answers

You don't need to check if the directory already exists, the method does it for you. If you check on MSDN :

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

like image 128
Phil-R Avatar answered Feb 18 '23 03:02

Phil-R


I would use a DirectoryInfo class, check if it exists, and maybe also if it does exist, check the permissions on the directory in case my current run-time permissions are not sufficient to access the contents or update the directory. You should apply exception handling to whichever method you go with; what if, for instance, a file exists with the name of the directory?

like image 41
Les Ferguson Avatar answered Feb 18 '23 04:02

Les Ferguson