Question

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);
        }
    }   
}
Was it helpful?

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.

OTHER TIPS

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top