EnsureDirectoryExists helper function

Below is a simple EnsureDirectoryExists helper function:
public static void EnsureDirectoryExists(string targetPath)
        {
            string dir = Path.GetDirectoryName(targetPath);
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
        }
posted @ Sunday, May 17, 2009 5:58 PM
Print

Comments on this entry:

# re: EnsureDirectoryExists helper function

Left by Max Schmeling at 6/4/2009 12:41 AM
Gravatar
Two things:
1. Why are you doing that if statement? Directory.CreateDirectory will just return if the directory already exists, so just call CreateDirectory and let it do its thing.
2. Now you have the EnsureDirectoryExists method on all strings when that namespace is imported even though *most* of your strings aren't going to be filenames or paths (i'm assuming) which isn't really a problem, but would be an area of annoyance for me.

# re: EnsureDirectoryExists helper function

Left by Max Schmeling at 6/4/2009 1:18 AM
Gravatar
For some reason I thought you were making an extension method... didn't look closely enough to see that there is no "this" in front of the parameter, so nevermind my issue #2. Issue #1 still applies though.

# re: EnsureDirectoryExists helper function

Left by Michael Freidgeim at 6/4/2009 8:03 AM
Gravatar
Thanks,Max,
I wasn't aware, that CreateDirectory does nothing, if path already exists.
Anyway I like explicit name of my function, because without documentation people can expect thtowing exception from CreateDirectory.

Your comment:



(not displayed)

 
 
 
 
 

Live Comment Preview:

 
«October»
SunMonTueWedThuFriSat
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678