The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 1,860 other subscribers

.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

One Response to “.NET/C#: do not do “if (!Directory.Exists(path)) Directory.CreateDirectory(path))””

  1. […] Half a year ago, I wrote about .NET/C#: do not do “if (!Directory.Exists(path)) Directory.CreateDirectory(path))”. […]

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.