.NET/C#: do not do “if (!Directory.Exists(path)) Directory.CreateDirectory(path))”
Posted by jpluimers on 2013/01/24
During code reviews, I often see people do things like this:
if (!Directory.Exists(directoryPath))
Directory.CreateDirectory(directoryPath);
or this:
DirectoryInfo directoryInfo = new DirectoryInfo(directoryPath);
if (!directoryInfo.Exists)
directoryInfo.Create();
You don’t need the if statements here.
The overload and plain Directory.CreateDirectory and the overload and plain DirectoryInfo.Create will do nothing if the directory already exists (that functionality, even if you explicitly pass DirectorySecurity.
That functionality has been in Directory.InternalCreateDirectory since the Microsoft released the first SSCLI Rotor in 2002.
So your code only needs to be like this:
Directory.CreateDirectory(directoryPath);
or this:
DirectoryInfo directoryInfo = new DirectoryInfo(directoryPath); directoryInfo.Create();
–jeroen






Delphi: do not do “if (not DirectoryExists(path)) then ForceDirectories(path))” « The Wiert Corner – irregular stream of stuff said
[…] Half a year ago, I wrote about .NET/C#: do not do “if (!Directory.Exists(path)) Directory.CreateDirectory(path))”. […]