Code to check if C# Directory Exists.

c# code to check if a directory exists and if it does not then go ahead and create it

Photo by Pankaj Patel on UnsplashPhoto by Pankaj Patel on Unsplash

C# code to check if a directory exists and if it does not then go ahead and create it.

I am also passing in file because this is pretty typical behavior when you are coding to a directory.

  • $"{filePath}... - you will also notice that I am using the new string interpolation wiht the "$" at the front
  • File.Delete - you may not need to do this but this was some code I built for testing so if the directory does exists then it is a good idea to delete those files before writing them again, I do not like to over write files

var fileName = "LOREM-IPSUM_LOREM_8f0s8d0fsd0.pdf";
var filePath = @"C:\Temp\";

if (Directory.Exists(filePath))
if (File.Exists($"

Update from Paul Congdon at LinkedIn

Here's an update to the code I've written to make it a litte better by Paul Congdon at LinkedIn. We worked together long ago in the early 2000's when the internet and start-up companies we're more on fire then they are today

He says => in the case of Directory, I have found that just calling CreateDirectory without an Exists check first is cleaner (and faster). Why is this? If the Directory already exists when calling CreateDirectory, it does not throw an error, it just returns the DirectoryInfo object as if it had been created.

In the case of File.Exists, it is subject to race conditions and a bit more complicated. For example, if you are wanting to open a file in the directory, just open it -- within a using -- with the FileMode.CreateNew param and then Read or Write depending on what you intend to do with the file. If you want exclusive access to the file, use a FileShare.None as well.

string path = "path to file";
using (var stream = File.Open(path, FileMode.CreateNew, FileAccess.Write, FileShare.None))
Share On

Travel, Food, Vikings, Travel, Vood, Vikings, Travel, Food, Vikings, Travel, Food, Vikings & Einstok Beer from Iceland

Leave a Comment