How can using this code

string sorece = folderBrowserDialog1.SelectedPath;
string target = folderBrowserDialog2.SelectedPath;
string sourceFile = System.IO.Path.GetFullPath(sorece);
string targetPath = System.IO.Path.GetFullPath(target);
System.IO.Directory.Move(sourceFile, targetPath);

i can move Folders ? please help

Recommended Answers

All 2 Replies

To create a directory(folder):

using System.IO;
class TestDirectory {
    public static void Main() {
        Directory.CreateDirectory("C:\\csharp");
    }
} 

to move a directory:
using System.IO;
class TestDirectory {
    public static void Main() {
        Directory.Move("C:\\csharp\\hello", "C:\\hello");
//"C:\\csharp\\hello" is the directory you want to move and 
//"C:\\hello" is where it's moved to
    }
}

to delete directory:
Directory.Delete("C:\\hello");
to rename/move file:
File.Copy( "c:\\friends.jpg", "c:\\temp\\abc.jpg");

@spdesigns, please use [code]

[/code] tags when posting code. It maintains formatting and makes your code much more readable.

@dan1992, you need to append the name of the folder you are moving to the end of your destination string. The Destination parameter of the Directory.Move method specifies the path of the folder after it has been moved. ie if you called Directory.Move("C:\a", "C:\b"); It wont move folder "a" inside folder "b" (ie "C:\b\a") it will attempt to move it so that "a" is "C:\b".
You would need to call Directory.Move("C:\a", "C:\b\a");
[/icode] if you wanted to move a into the destination folder.
The following minor change will correct your code:

string sorece = folderBrowserDialog1.SelectedPath;
    string target = folderBrowserDialog2.SelectedPath;
    string sourceFile = System.IO.Path.GetFullPath(sorece);

    string FolderName = System.IO.Path.GetFileName(sorece); //get name of source folder

    string targetPath = Path.Combine(System.IO.Path.GetFullPath(target), FolderName); //append folder name to destination
    System.IO.Directory.Move(sourceFile, targetPath);

This is still not a complete solution. I would suggest using Directory.Exists to check the target path does not already exist before trying to move the file..alternatively, wrap it all up ina try...catch block to catch errors if you try to use file paths that already exist.

EDIT: Before anyone points it out (or for anyone who doesnt know already), you would need to use Directory.Move(@"C:\a", @"C:\b") or Directory.Move("C:\\a", "C:\\b"). I left out the escapes to avoid overly complicating the example :p

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.