24

I am concatenating a number of variables and I want to save that string as a file path.

Is there a way it will automatically create all appropriate directories if they don't exist without having to check "if exists" on each one

For example.

"C:\" + a + "\" + b+ "\" + d + "\" + d + ".txt"
hage
  • 5,966
  • 3
  • 32
  • 42
leora
  • 188,729
  • 360
  • 878
  • 1,366
  • Possible duplicate of [If a folder does not exist, create it](http://stackoverflow.com/questions/9065598/if-a-folder-does-not-exist-create-it) – Michael Freidgeim Nov 28 '16 at 03:04

2 Answers2

70

Use new FileInfo(path).Directory.Create().

(This creates anything in the hierarchy that's required. If the directory already exists it does nothing.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • As you can not be sure to find a FileInfo for the path I would add a conditional access: `new FileInfo(destFileName).Directory?.Create();` – DaveM Sep 18 '20 at 12:59
  • 1
    @DaveM: Can you give an example where `FileInfo.Directory` will return null? I'm not sure what you mean by "can not be sure to find a FileInfo for the path", but in at least some failure cases, an exception will be thrown rather than returning null - I can't see any documentation for cases where this will return null. – Jon Skeet Sep 18 '20 at 15:30
  • Yes ur absolutely right. Sorry I made a mistake here. As you mentioned the docs say: _DirectoryNotFoundException_ ... when _The specified path is invalid, such as being on an unmapped drive_. There does not seem to be a case `FileInfo.Directory` will return null – DaveM Sep 23 '20 at 07:08
15

using System.IO;
....
Directory.CreateDirectory(@"c:\temp\a\b\c\d\e");

shahkalpesh
  • 33,172
  • 3
  • 63
  • 88