Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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\

?

like image 962
Exitos Avatar asked Aug 03 '11 11:08

Exitos


People also ask

How does file move work?

Move(String, String, Boolean) Moves a specified file to a new location, providing the options to specify a new file name and to overwrite the destination file if it already exists.

Does file move overwrite?

File. Move() doesn't support overwriting of an existing file. In fact, it will throw an IOException if a file with the same path as sourceDestFilename already exists.


2 Answers

Use System.IO.Directory.CreateDirectory

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

like image 75
alun Avatar answered Oct 02 '22 14:10

alun


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

like image 21
Tony The Lion Avatar answered Oct 02 '22 14:10

Tony The Lion