Wednesday, June 19, 2019

c# SFTP download all files



        public static void DownloadAllFile()
        {
            try
            {
                string host = Properties.Settings.Default.SFTP;
                string username = Properties.Settings.Default.SFTP_UserName;
                string password = Properties.Settings.Default.SFTP_Password;

                string remoteDirectory = Properties.Settings.Default.SFTP_Path;
               
                string downloadDirectory = Properties.Settings.Default.DownloadDirectory;


                using (SftpClient sftp = new SftpClient(host, username, password))
                {
                    try
                    {
                        sftp.Connect();
                        var files = sftp.ListDirectory(remoteDirectory);

                        foreach (var file in files)
                        {
                            string fileName = file.Name;
                            if (fileName.Length > 2)
                            {
                                //Only download file if the file name begins with XX
                                if (fileName.Substring(0, 2) == "XX")
                                {
                                    Console.WriteLine(file.Name);
                                    using (Stream fileStream = File.OpenWrite(downloadDirectory + file.Name))
                                    {
                                        sftp.DownloadFile(file.FullName, fileStream);
                                    }
                                }
                            }
                        }

                        sftp.Disconnect();
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("An exception has been caught " + e.ToString());
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("General Exception: {0}", e);
            }
        }

No comments:

Post a Comment