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?
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With