FileInfo finds file, but File.Copy cannot find the file

1.1k views Asked by At

I am trying to find a file with the last write date and copy it to a different location. It finds the file correctly, but when I try to copy it, it can't find the file it just found. This is in a SSIS script task.

DirectoryInfo directory = new DirectoryInfo(@"path");
FileInfo[] files = directory.GetFiles();

//files that have been written to in the last 3 days
DateTime lastWrite = DateTime.Now.AddDays(-3); 

foreach (FileInfo latestFile in files)
{  
    // if its the correct name
    if (latestFile.Name.StartsWith("OMC")) 
    {
        // if its in the last 3 days
        if (latestFile.LastWriteTime > lastWrite) 
        {    
            lastWrite = latestFile.LastWriteTime;

            // this correctly find the file and puts it into the file variable.
            file = latestFile.ToString(); 

            // this errors out saying it cannot find the file.
            // (Does not even go to the outputFile)
            File.Copy(file, outputFile, true); // <- error

            //backs the file up 
            File.Copy(file, backupfile, true);
        }
    }   
}
3

There are 3 answers

0
Arian Motamedi On BEST ANSWER

FileInfo.ToString() returns the name of the file, but in order to copy it, you need the full path. Change

file = latestFile.ToString();

To

file = latestFile.FullName;

And give it a shot.

2
usr On

What does latestFile.ToString() evaluate to? That is a strange way to obtain the path.

Use FileInfo.FullName like the docs indicate.

You can use the debugger to find such bugs yourself.

0
D Stanley On

You may need to construct the full path instead of using Fileinfo.ToString():

file = latestFile.FullName; 

From MSDN:

there are cases where the string returned by the ToString method does not represent the fully qualified path. For example, when you create a FileInfo object using the GetFiles method, the ToString method does not represent the fully qualified path.