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,832 other followers

.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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

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

 
%d bloggers like this: