1

I am downloading from SFTP and want to check if the file exists in the folder "directory @"D:..." or not

 using (SftpClient sftp = new SftpClient(Host, Port, Username, Password))

            {
                sftp.Connect();

                var files = sftp.ListDirectory(RemoteFileName);

                string downloadFileNames = string.Empty;

                foreach (var file in files)
                {
                    if (file.FullName.EndsWith(".gz"))
                    {
                        using (Stream fileStream = File.Create(Path.Combine(directory, file.Name)))
                        {

                            sftp.DownloadFile(file.FullName, fileStream);
                        }
                    }
                    downloadFileNames += file.Name;
                }
            }
Selaka Nanayakkara
  • 3,296
  • 1
  • 22
  • 42
Ben Omran
  • 31
  • 8

1 Answers1

2

Based on your comment:

i don't want evey time to download the same files i want to check if its arleady downloaded then not download it again

I am assuming that you want to only download files that you have not previously downloaded.

In order to achieve this, use File.Exists to verify whether you already downloaded the file to a location:

foreach (var file in files)
{
    if (file.FullName.EndsWith(".gz"))
    {
        var targetFilename = Path.Combine(directory, file.Name);

        if (!File.Exists(targetFilename))
        {
            using (Stream fileStream = File.Create(targetFilename))
            {
                sftp.DownloadFile(file.FullName, fileStream);
            }
            downloadFileNames += file.Name;
        }
    }
}

This verifies whether the target file exists before downloading it from the SFTP server.

Martin
  • 16,093
  • 1
  • 29
  • 48