Whats the easiest way to ensure folder exist before I do a File.Move?

21,848

Solution 1

Use System.IO.Directory.CreateDirectory

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

Solution 2

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

Solution 3

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.

Share:
21,848
Exitos
Author by

Exitos

Updated on August 04, 2020

Comments

  • Exitos
    Exitos almost 4 years

    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\

    ?