Create Directory Elegantly RRS feed

  • Question

  • Lets say I have a path "C:\\something\\insomthing\\moreinsomething". I would like to ensure that this directory exists. Is there an elegant way to create this directory structure IF it doesn't already exist? How would you do this? I rather avoid using loops if its possible

    Thursday, July 28, 2011 1:41 PM


All replies

  • Directory.CreateDirectory




    • Proposed as answer by Matthew Watson Thursday, July 28, 2011 2:17 PM
    • Marked as answer by Cookie Luo Tuesday, August 2, 2011 1:58 AM
    Thursday, July 28, 2011 2:01 PM
  • That will work because Directory.CreateDirectory() recursively creates the directory structure.

    If the directory already exists, it does nothing.

    Do NOT do this:

    if (!Directory.Exists(dirname))

    Just call Directory.CreateDirectory(). It's pointless to check if it exists first since Directory.CreateDirectory() will check again anyway - so you've just wasted a call.

    Thursday, July 28, 2011 2:20 PM
  • Exactly, here is an example:


          // "C:\\something\\insomthing\\moreinsomething"
          string path = @"C:\";
          string dir1 = "something";
          string dir2 = "insomething";
          string dir3 = "moreinsomething";
          path = Path.Combine(path, dir1);
          if (!Directory.Exists(path))
          path = Path.Combine(path, dir2);
          if (!Directory.Exists(path))
          path = Path.Combine(path, dir3);
          if (!Directory.Exists(path))
          //now all directories are created!

    Thursday, July 28, 2011 2:22 PM
  • Argh! You just did the "if (!Directory.Exists())" thing! ;)

    Also, you do NOT need to create each part of the dir structure separately like that; CreateDirectory() does it for you.

    Your code sample is better written like this:


    Thursday, July 28, 2011 2:27 PM
  • Mitja,

    just do Directory.CreateDirectory(StringFullPath), it will create all the folders needed and will throw *no* exception, if one or more of them already exist.

    See: http://msdn.microsoft.com/en-us/library/9y2ywx4s.aspx



    Thursday, July 28, 2011 2:30 PM
  • Argh! You just did the "if (!Directory.Exists())" thing! ;)


    Why, you have this kind of expression?


    And thx for tell me that I can do all folders at ones (really didnt know that, actually didint even try it before).

    Thursday, July 28, 2011 2:43 PM