N0xus N0xus - 6 months ago 72
C# Question

File.Exists returns true but copying found file fails

I have the following lines of code:

protected void MoveFilesToInBound(string filePath, string fileName, DateTime? reportingRun)
{
var dateValue = reportingRun.Value.ToString("yyyyMMdd");
var file = fileName + "_" + dateValue + ".csv";

if (File.Exists(Path.Combine(filePath, file)))
{
File.Copy(file, InputFolder);
}
}


Stepping through my code I can see that my target file is found in my target file location. However, when it comes from copying my file to my input folder (which is correct) it fails telling me:
Could not find file 'myFile_20170831.csv'
.

What's confusing me is that I don't understand why this is failing. If the file wasn't there, surely it wouldn't even reach the
File.Copy
line which is where it throws the error.

Can someone please shed some light on this? I have double and tripled checked all my locations and they do match up. I just don't get why the file isn't copying from my first location to my second.

Answer Source

Well, you are not using the same paths...:

if (File.Exists(Path.Combine(filePath, file)))
{
    File.Copy(file, InputFolder);
}

Path.Combine(filePath, file) is, hopefully, not the same as file. Didn't you mean to use:

if (File.Exists(Path.Combine(filePath, file)))
{
    File.Copy(Path.Combine(filePath, file), InputFolder);
}

I said "hopefully" because, if file was a full path ("C:\.."), Path.Combine would return file instead of the combination.

Also, in order to gain some performance, you should be using:

string filePath = Path.Combine(filePath, file);
if (File.Exists(filePath))
{
    File.Copy(filePath, InputFolder);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download