为什么File.Move没有按预期工作?

Joh*_*rar 0 c#

我试图将所有文件移动rootFolderPathdestinationPath

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());
}
Run Code Online (Sandbox Code Playgroud)

显然MessageBox.Show(file);显示我的根文件夹路径(正常情况下)但MessageBox.Show(destination);显示我同样的事情.

是什么赋予了?它只是将我file从我的根文件夹中移动到同一个文件夹中.我没有得到什么东西?

wak*_*aka 7

您正在将destinationPath完整的文件路径与file:

string destination = Path.Combine(destinationPath, file);
Run Code Online (Sandbox Code Playgroud)

这将只用原始文件路径覆盖目标(因为"C:\ desitnation\C:\ source\filename.txt"不是有效路径).

相反,您只需要像这样的文件名:

string destination = Path.Combine(destinationPath, Path.GetFileName(file));
Run Code Online (Sandbox Code Playgroud)