c# code to check if a directory exists and if it does not then go ahead and create it
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.
var fileName = "LOREM-IPSUM_LOREM_8f0s8d0fsd0.pdf";
var filePath = @"C:\Temp\";
if (Directory.Exists(filePath))
{
if (File.Exists($"{filePath}{fileName}"))
{
File.Delete($"{filePath}{fileName}");
}
}
else
{
Directory.CreateDirectory(filePath);
}
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))
{}