John Pietrar
John Pietrar

Reputation: 543

Why is File.Move not working as expected?

I am trying to move all files from rootFolderPath to destinationPath

try
{
    string rootFolderPath = @"D:\Log_siteq\";
    if (!Directory.Exists(Path.Combine(@"D:\Log_takaya\" + comboBox1.SelectedItem.ToString())))
    {
        System.IO.Directory.CreateDirectory(Path.Combine(@"D:\Log_takaya\" + comboBox1.SelectedItem.ToString()));
    }


    string destinationPath = Path.Combine(@"D:\Log_takaya\" + comboBox1.SelectedItem.ToString() );
    string fileTypes = @"*.*";
    string[] fileList = System.IO.Directory.GetFiles(rootFolderPath, fileTypes);
    foreach (string file in fileList)
    {
        string ext = Path.GetExtension(file);
        string destination = Path.Combine(destinationPath,file);                 
        File.Move( file,destination);
        MessageBox.Show(file);
        MessageBox.Show(destination);
    }
}
catch(Exception ex)
{
    MessageBox.Show(ex.ToString());
}

Apparently MessageBox.Show(file); shows me my root folder path ( as is normal) but MessageBox.Show(destination); is showing me the same thing.

What gives? It just moves my file from my root folder in the same folder.Am I not getting something?

Upvotes: 0

Views: 2768

Answers (1)

waka
waka

Reputation: 3417

You are combining the destinationPath with the complete file path of file:

string destination = Path.Combine(destinationPath, file);

which will just overwrite the destination with the original file path (because "C:\desitnation\C:\source\filename.txt" isn't a valid path).

Instead, you need only the file name like this:

string destination = Path.Combine(destinationPath, Path.GetFileName(file));

Upvotes: 7

Related Questions