I want to check if a folder exists and if not then create it. But I don’t know if the path supplied will even valid. When the path is not valid the following happens.
string path = "this is an invalid path";
if (!Directory.Exists(path))
Directory.CreateDirectory(path); //Exception thrown here
If you supply an invalid path, it will throw a DirectoryNotFoundException exception.
How can I stop this exception from occurring? I don’t want to use a try-catch. I want to detect that this exception will occur even before the exception happens.
The explanation for the failure of your code is that the path is invalid. The documentation says:
Trying to predict in advance whether or not a directory can be created is a devil of a job. You’d need to account for security, OS name rules and limits, file system name rules and limits, and whether or not drives are mapped. And probably lots more concerns. I would not contemplate re-implementing what the system provides for free.
In any case, whilst you can call
Directory.Exists, you do still need to allow for an exception being thrown. If the file system changes between the call toDirectory.Existsand the subsequent call toDirectory.CreateDirectory, then an exception will be raised. For example, if another process creates the directory that you are trying to create. Granted, this is a rather unlikely event, but it’s perfectly possible.In summary, the best option, by a distance, is to catch the exception. As the well known saying goes, it’s better to ask for forgiveness than to ask for permission.