move file create directory.

时间:2023-03-09 02:53:52
move file create directory.

If we want to move file to the directory that does not exist,and if we perform a File.Move,it will result return an error shows that 'The path is not exist'.

So,we have to create a new directory using System.IO.Directory.CreateDirectory.

Here is an example:

 string path = txt_path.Text.Trim(); //Root of the path that contains files to be move.
System.IO.DirectoryInfo dirRoot = new System.IO.DirectoryInfo(path);
if (!dirRoot.Exists) {
MessageBox.Show("The directory is not exist!");
return;
}
System.IO.FileInfo[] files = dirRoot.GetFiles();
foreach (var file in files) { //Iterate create new directories.
System.IO.DirectoryInfo dir = System.IO.Directory.CreateDirectory(file.DirectoryName + "\\" + System.IO.Path.GetFileNameWithoutExtension(file.Name));
file.MoveTo(dir.FullName + "\\" + file.Name);
}

Ref:http://*.com/questions/6925561/whats-the-easiest-way-to-ensure-folder-exist-before-i-do-a-file-move