how to stop Directory.CreateDirectory creating parents?

606 views Asked by At

I know that Directory.CreateDirectory actually creates parents, so how can I STOP this from happening? i.e. is there a mode that I can utilise like a stricter way of doing so, the reason is that I have a watch program watching the parent top tree dir and it goes beserk if Directory.CreateDirectory makes more than one dir at a time.

Is there an equivalent to Directory.CreateDirectory which will NOT make parents?

2

There are 2 answers

0
Mr Heelis On BEST ANSWER
List<string> missingDirectories = null;
private void MakeParents(string path)
{
    missingDirectories = new List<string>();
    missingDirectories.Add(path);
    parentDir(path);
    missingDirectories = missingDirectories.OrderBy(x => x.Length).ToList<string>();
    foreach (string directory in missingDirectories)
    {
        Directory.CreateDirectory(directory);
    }        
}
private void parentDir(string path)
{
    string newPath = path.Substring(0, path.LastIndexOf(Path.DirectorySeparatorChar));
    if (!Directory.Exists(newPath))
    {
        missingDirectories.Add(newPath);
        parentDir(newPath);
    }
}

this does it, the issue is that if you want to "gently" roll up the paths one dir at a time making them, something like this is the only way you can do it :/

0
Serhiy Chupryk On

Do you understand what for you need such method? It seems like you don't want to create all folders needed to create your target folder, like: C:\this\is\your\path\TargetFolder In this case you can just do the following:

const string path = @"C:\this\is\your\path";
if (Directory.Exists(path))
{
    Directory.CreateDirectory(Path.Combine(path, "TargetDirectory"));
}

If you have other purpose for that method, please help us to understand which one