Solved: How do I fix C# WinSCP code “No such file” errors on multiple downloads

Problem Symptom

I have the following C# code that uses WinSCP to download files. I had to point it to a set of files with a different prefix. In this case, there could be more than one match on the SFTP server. This code correctly downloads the first matching file but then exits via the catch with the message “No such file” when it continues onto the next match. Commenting out the download code stops that message. How to modify the c# code to download multiple files?

foreach (var entry in dirContents)
                {
                    // Check to see if the base filename of the remote file contains "hm_pos_"
                    if (entry.Name.Contains("hm_pos_"))
                    {
                        Console.WriteLine(" Filename : " + entry.Name);
                        dateOnly = entry.Attributes.LastWriteTime.Date;

                        // Search for PO files created today
                        if (entry.Attributes.LastWriteTime.Date == dateToday)
                        {
                            FilenameToSave = entry.FullName;
                            FilenameToSave = FilenameToSave.Replace("/upload/", "");        /* Remove the folder prefix from the filename */
                        }
                        if (FilenameToSave.Length > 0)
                        {
                            // Using the most recent filename, create a new local file with FileStream, and then download the remote file data into the local file
                            using (FileStream localFile = new FileStream(FilenameToSave, FileMode.Create))
                            {

                                sftpClient.DownloadFile(FilenameToSave, localFile);
                            }
                        }
                    }
                }

Follow the below solution steps to resolve “No such file” issue when download multiple files using WinSCP.

Solution

Comment out the download code would fix the problem if the “No such file” error is occurring because it’s trying to download a file that doesn’t exist.

It seems like you might be removing the path from the FilenameToSave in order to get its base filename, but then you’re trying to download a file without specifying that path.

Try changing:

sftpClient.DownloadFile(FilenameToSave, localFile);

to:

sftpClient.DownloadFile(entry.FullName, localFile);