无法将文件移动到另一个文件夹。错误在错误的路径上返回

时间:2015-12-28 03:18:58

标签: c# path windows-services

这是我将excel文件移动到具体的代码。

       if (Directory.GetFiles(destinationPath, "*.xls").Length != 0)
            {
                //Move files to history folder
                string[] files = Directory.GetFiles(destinationPath); //value -- D://FS//
                foreach (string s in files)
                {
                    var fName = Path.GetFileName(s); //12232015.xls
                    var sourcePath = Path.Combine(destinationPath, fName);
                    var destFile = Path.Combine(historyPath, fName); // -- D://FS//History
                    File.Move(fName, destFile);
                }
            }

但它的错误  Could not find file 'D:\Project\ProjectService\bin\Debug\12232015.xls'.

为什么它在我的项目下找不到我设置的特定文件夹?

谢谢。

2 个答案:

答案 0 :(得分:1)

存在逻辑错误。变化

File.Move(fName, destFile);

File.Move(sourcePath, destFile);

因为fName只包含文件名而不是完整路径。该文件在工作目录中检查。

答案 1 :(得分:1)

您只使用文件名:

var fName = Path.GetFileName(s); //12232015.xls
//...
File.Move(fName, destFile);

如果没有完整路径,系统将查看当前工作目录。这是执行应用程序的目录。

您应该使用源文件的完整路径:

File.Move(sourcePath, destFile);

明确指定完整路径几乎总是最好的方法。众所周知,相对路径难以管理。