Search code examples
c#.netfilefileinfodirectoryinfo

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


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

Solution

  • 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.