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);
}
}
}
}
}
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.)
See more on this question at Stackoverflow