rjps12
rjps12

Reputation: 605

Cannot move a file to another folder. Error returns on a wrong path

Here's my code in moving excel file to be specific..

       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);
                }
            }

But it gets an error of Could not find file 'D:\Project\ProjectService\bin\Debug\12232015.xls'.

Why it finds under my project not on the specific folder i set?

Thank you.

Upvotes: 1

Views: 610

Answers (2)

David
David

Reputation: 218798

You're only using the name of the file:

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

Without a complete path, the system will look in the current working directory. Which is the directory where the application is executing.

You should use the entire path for the source file:

File.Move(sourcePath, destFile);

Explicitly specifying the full path is almost always the best approach. Relative paths are notoriously difficult to manage.

Upvotes: 1

AEonAX
AEonAX

Reputation: 511

There is an Logical error. Change

File.Move(fName, destFile);

to

File.Move(sourcePath, destFile);

as fName only contains file name and not fullpath. The file is checked in working directory.

Upvotes: 1

Related Questions