Search code examples
c#parentcreate-directory

how to stop Directory.CreateDirectory creating parents?


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?


Solution

  • 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 :/