namespace FileMove2
{
class Program
{
static void Main(string[] args)
{
Console.Write("Which folder would you like to move files from?");
string sourcePath = Console.ReadLine();
Console.Write("Which folder would you like to move files to?");
string targetPath = Console.ReadLine();
MoveDirectory(sourcePath, targetPath);
}
static void MoveDirectory(string sourcePath, string targetPath)
{
if (!System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
}
if (System.IO.Directory.Exists(sourcePath))
{
string[] files = System.IO.Directory.GetFiles(sourcePath, "*.*", System.IO.SearchOption.AllDirectories);
foreach (string f in files)
{
System.IO.File.Move(f, targetPath);
}
}
}
}
}
Asked
Active
Viewed 523 times
-2
-
2Are you getting an error? What error? – Andrei Mar 20 '14 at 19:50
-
duplicates http://stackoverflow.com/questions/58744/best-way-to-copy-the-entire-contents-of-a-directory-in-c-sharp – Yaugen Vlasau Mar 20 '14 at 19:53
2 Answers
1
You should be doing this instead:
System.IO.Directory.Move(@"C:\Users\Public\public\test\", @"C:\Users\Public\private");
Where your sourcePath is the first param and targetPath is the second accordingly.
References: Microsoft MSDN

João Pinho
- 3,725
- 1
- 19
- 29
1
The problem is that File.Move
takes two filenames, whereas you're providing a filename and a directory.
You can fix your code by creating the appropriate target filename:
string targetFile = Path.Combine(targetPath, Path.GetFileName(f));
File.Move(f, targetFile);
(As noted by João Pinho, Directory.Move
may do what you want, but the above explains why you're getting an error, and will help if your real situation is more complicated.)

Jon Skeet
- 1,421,763
- 867
- 9,128
- 9,194