39

I have a folder structure:

C:\Temp [completely empty]

And I have a file that I want to move to

C:\Temp\Folder1\MyFile.txt

If I perform a File.Move I will get an error saying that this folder doesnt exist.

Is there any C# method that will create all the folders up to that point so:

C:\Temp\Folder1\

?

Exitos
  • 29,230
  • 38
  • 123
  • 178

3 Answers3

76

Use System.IO.Directory.CreateDirectory

Addtional note: You don't have to check if it exists first. CreateDirectory will do the right thing regardless.

alun
  • 3,393
  • 21
  • 26
10
If Directory.Exists("somedir")

See here for more info.

To create a directory if it doesn't exist

Directory.CreateDirectory("path of dir");

It will create all dirs and subdirs, see here

Tony The Lion
  • 61,704
  • 67
  • 242
  • 415
5

You can use Directory.CreateDirectory() for that. Apparently, it creates all directories in the path.

Keep in mind that between the time you create there directory and the time when you move the file, somebody could have deleted the directory. So there is no way to be absolutely sure that the directory will actually exists when you try to move the file. One possible exception is using filesystem transactions.

svick
  • 236,525
  • 50
  • 385
  • 514
  • Your comment about not being able to be absolutely sure is wrong. You can clearly check to see if it exists before you do anything with the folder. Considering the application runs faster then a human can delete a folder, and provided you always check to see if the folder exists, the folder will always be there. – Security Hound Aug 03 '11 at 11:29
  • 7
    Technically he's correct, there is a race condition between the check and the move. In practice, this isn't something I would worry about in my application as it would be next to impossible to encounter. – Brian Dishaw Aug 03 '11 at 11:56
  • 9
    @Rahmound, what if the other one is not human, but some other application? For example one that periodically cleans the Temp directory? – svick Aug 03 '11 at 13:54