Ejemplo n.º 1
0
        /// <summary>
        /// Downloads a file in the desktop synchronously
        /// </summary>
        /// <param name="options"></param>
        /// <param name="fileName">文件名称 file_server.txt</param>
        public static void DownloadFile(FtpClientOptions options, string fileName)
        {
            // Path to file on SFTP server
            var pathRemoteFile = Path.Combine(options.RemoteDir, fileName);
            // Path where the file should be saved once downloaded (locally)
            var pathLocalFile = Path.Combine(options.LocalDir, fileName);

            using (var sftp = new SftpClient(options.Host, options.UserName, options.Password))
            {
                try
                {
                    sftp.Connect();

                    Console.WriteLine("Downloading {0}", pathRemoteFile);

                    using (Stream fileStream = File.OpenWrite(pathLocalFile))
                    {
                        sftp.DownloadFile(pathRemoteFile, fileStream);
                    }

                    sftp.Disconnect();
                }
                catch (Exception er)
                {
                    Console.WriteLine("An exception has been caught " + er);
                }
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        ///  List a remote directory in the console.
        /// </summary>
        /// <param name="options">ftp服务器配置信息</param>
        public static string ListFiles(FtpClientOptions options)
        {
            var fileNameStr = string.Empty;

            using var sftp = new SftpClient(options.Host, options.UserName, options.Password);
            try
            {
                sftp.Connect();

                var files = sftp.ListDirectory(options.RemoteDir);

                foreach (var file in files)
                {
                    fileNameStr += $"{file.FullName}{Environment.NewLine}";
                }

                sftp.Disconnect();
                return(fileNameStr);
            }
            catch (Exception e)
            {
                return(e.Message);
            }
        }