public string DownloadFile(string ftpDirectory, string sourcePath)
        {
            if (!_sftpClient.IsConnected)
            {
                _sftpClient.Connect();
            }

            var filePath = Path.GetTempFileName();

            try
            {
                using (var fileStream = File.OpenWrite(filePath))
                {
                    _sftpClient.DownloadFile(ftpDirectory + "/" + sourcePath, fileStream);
                }

                return(filePath);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                _sftpClient.Disconnect();
            }
        }
Beispiel #2
0
 public bool DownloadFile(string From_File, string To_File, bool IsErrorLogMode = false)
 {
     if (!IsConnected)
     {
         return(false);
     }
     else if (!SFTP_Server.IsConnected)
     {
         SFTP_Server.Connect();
     }
     try
     {
         IsDownloading = true;
         using (Stream fs = File.OpenWrite(To_File))
             SFTP_Server.DownloadFile(From_File, fs, (ulong upSize) =>
             {
                 if (!IsDownloading)
                 {
                     fs.Close();
                 }
             });
         IsDownloading = false;
         return(true);
     }
     catch (Exception e)
     {
         if (IsErrorLogMode)
         {
             Sub_Code.Error_Log_Write(e.Message);
         }
         IsDownloading = false;
         return(false);
     }
 }
Beispiel #3
0
        public LocalPath Download(string src)
        {
            var       path = string.IsNullOrWhiteSpace(_rootPath) ? src : LexicalPath.Combine(_rootPath, src);
            LocalPath res  = new LocalPath(LocalUtils.GetTempFileName());

            using (var stream = File.OpenWrite(res.Path))
                _client.DownloadFile(path, stream);
            return(res);
        }
Beispiel #4
0
        /// <summary>
        /// Upload files to remote target path
        /// </summary>
        /// <param name="sourcePath">source path</param>
        /// <param name="target">file steam to write</param>
        /// <returns>success or not</returns>
        public bool DownloadFiles(string sourcePath, FileStream target)
        {
            bool ret = false;

            if (IsSftpClientActive())
            {
                sftpClient.DownloadFile(sourcePath, target);
                ret = true;
            }
            return(ret);
        }
 internal void DownloadFile(string remotePath, MemoryStream stream)
 {
     if (_sftpClient is NoAuthenticationSftpClient noAuthenticationSftpClient)
     {
         noAuthenticationSftpClient.RunCommand(new DownloadFile(remotePath, stream));
     }
     else
     {
         _sftpClient.DownloadFile(remotePath, stream);
     }
 }
Beispiel #6
0
        private void Form1_onConnectionSuccess(object sender, EventArgs e)
        {
            using (var outputFile = new FileStream(Path.Combine(_savePath, "verbose.txt"), FileMode.Create))
            {
                _client.DownloadFile("/home/pi/Atum/Logging/verbose.log", outputFile);
            }

            using (var outputFile = new FileStream(Path.Combine(_savePath, "verbose-old.txt"), FileMode.Create))
            {
                _client.DownloadFile("/home/pi/Atum/Logging/verbose-old.log", outputFile);
            }
        }
Beispiel #7
0
 public Task <string> GetAsync(string source, string destination)
 {
     // 将在线程池上运行的指定工作队列, 并返回该工作句柄
     return(Task.Run(
                () =>
     {
         using (var saveFile = File.OpenWrite(destination))
         {
             sftp.DownloadFile(source, saveFile);
             return destination;
         }
     }));
 }
        /// <summary>
        /// Downloads files at sftp folder location to temp folder path on server
        /// </summary>
        /// <param name="sftpFolderLocatn"></param>
        /// <param name="folderDownloadPath"></param>
        /// <param name="fileNmesToMtchStr"></param>
        /// <param name="deleteFileFrmSrver"></param>
        /// <returns>return false if failed to find any files at location otherwise true</returns>
        public bool DownloadFilesFromSftp(string sftpFolderLocatn, string folderDownloadPath, string fileNmesToMtchStr, bool deleteFileFrmSrver)
        {
            try
            {
                if (objSftpClient == null)
                {
                    return(false);
                }
                objSftpClient.Connect();
                if (objSftpClient.IsConnected)
                {
                    var csvFiles = objSftpClient.ListDirectory(sftpFolderLocatn).Where(x => x.Name.ToLower().IndexOf(fileNmesToMtchStr) != -1);
                    if (csvFiles == null)
                    {
                        return(false);
                    }

                    foreach (var file in csvFiles)
                    {
                        using (var stream = new FileStream(Path.Combine(folderDownloadPath, file.Name), FileMode.Create))
                        {
                            objSftpClient.DownloadFile(file.FullName, stream);
                        }
                        if (deleteFileFrmSrver)
                        {
                            objSftpClient.Delete(file.FullName);
                        }
                    }
                }
                else
                {
                    throw new Exception("Error: GetFileFromSftp() - Could not connect to sftp server");
                }
            }
            catch (Exception ex)
            {
                throw  new Exception(String.Format("Error downloading files from sftp server. Ex: {0}", ex.Message));
            }
            finally
            {
                if (objSftpClient != null)
                {
                    if (objSftpClient.IsConnected)
                    {
                        objSftpClient.Disconnect();
                    }
                }
            }

            return(true);
        }
        void IFtpSession.Download(string remotePath, string localPath, bool overwrite, bool recursive)
        {
            if (string.IsNullOrWhiteSpace(remotePath))
            {
                throw new ArgumentNullException(nameof(remotePath));
            }
            if (string.IsNullOrWhiteSpace(localPath))
            {
                throw new ArgumentNullException(nameof(localPath));
            }

            FtpObjectType objectType = ((IFtpSession)this).GetObjectType(remotePath);

            if (objectType == FtpObjectType.Directory)
            {
                IEnumerable <Tuple <string, string> > listing = GetRemoteListing(remotePath, localPath, recursive);

                foreach (Tuple <string, string> file in listing)
                {
                    string directoryPath = Path.GetDirectoryName(file.Item1);
                    if (!Directory.Exists(directoryPath))
                    {
                        Directory.CreateDirectory(directoryPath);
                    }

                    using (Stream fileStream = File.OpenWrite(file.Item1))
                    {
                        _sftpClient.DownloadFile(file.Item2, fileStream);
                    }
                }
            }
            else
            {
                if (objectType == FtpObjectType.File)
                {
                    if (File.Exists(localPath) && !overwrite)
                    {
                        throw new IOException(Resources.FileExistsException);
                    }

                    using (Stream fileStream = File.OpenWrite(localPath))
                    {
                        _sftpClient.DownloadFile(remotePath, fileStream);
                    }
                }
                else
                {
                    throw new NotImplementedException(Resources.UnsupportedObjectTypeException);
                }
            }
        }
Beispiel #10
0
 public bool Download(string sourceFile, string targetFile)
 {
     try
     {
         using (var fs = File.Create(targetFile))
         {
             _sftp.DownloadFile(sourceFile, fs);
         }
         return(true);
     }
     catch (Exception e)
     {
         throw new Exception(e.Message, e);
     }
 }
        // get file from SFTP and return string
        public void getFromSFTP(string hostname, int port, string userName, string password, string tempFileName, string fileName)
        {
            try
            {
                mySFTPClient = new SftpClient(hostname, port, userName, password);
                myFileStream = new FileStream(tempFileName, FileMode.Create);

                mySFTPClient.Connect();
                mySFTPClient.DownloadFile(fileName, myFileStream, DownloadDone); // DownloadDone is Action<ulong>

                return;
            }
            catch (Exception e)
            {
                CrestronConsole.PrintLine("Document.getFromSFTP() Exception {0}", e);
                CrestronConsole.PrintLine("Document.getFromSFTP() Host {0}, Port {1}, User {2}, fileName {3}",
                                          hostname, port, userName, fileName);
                throw;
            }
            finally
            {
                mySFTPClient.Disconnect();
                myFileStream.Close();
            }
        }
Beispiel #12
0
        /// <summary>
        /// Descarga archivo de servidor a un directorio local.
        /// </summary>
        /// <param name="filePath">Ruta de Archivo en servidor remoto.</param>
        /// <param name="destinationPath">Ruta de descarga local.</param>
        /// <returns>Logrado o no logrado.</returns>
        /// <remmarks>No validado.</remmarks>
        public bool Download(string filePath, string destinationPath)
        {
            bool result = false;

            using (SftpClient client = new SftpClient(Host, User, Pass))
            {
                client.Connect();

                if (client.IsConnected)
                {
                    SftpFile file = client.Get(filePath);
                    if (!file.IsDirectory)
                    {
                        string path = $"{destinationPath}/{file.Name}";
                        using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite))
                        {
                            client.DownloadFile(file.FullName, fs);
                        }

                        result = true;
                    }

                    client.Disconnect();
                }
            }

            return(result);
        }
Beispiel #13
0
        public PersistBackup GetBackup(string server, string backupName)
        {
            var servers = _config.GetSection("Servers");
            var entry   = servers.GetSection(server);

            if (entry == null)
            {
                return(null);
            }
            PersistBackup backup   = null;
            var           hostName = entry.Key;
            var           password = entry.Value;

            using (var client = new SftpClient(hostName, "arma3-public", password))
            {
                client.Connect();
                if (client.Exists(filePath))
                {
                    var mem = new MemoryStream();
                    client.DownloadFile(filePath, mem);
                    mem.Position = 0;
                    backup       = PersistBackup.Read(mem, client.GetLastWriteTime(filePath), hostName).FirstOrDefault(b => b.Name == backupName);
                }
                client.Disconnect();
            }
            return(backup);
        }
Beispiel #14
0
        private static List <SftpFile> DownloadFiles(SftpClient sftpClient, string destLocalPath)
        {
            Directory.CreateDirectory(destLocalPath);
            IEnumerable <SftpFile> files    = sftpClient.ListDirectory(".");
            List <SftpFile>        NewFiles = new List <SftpFile>();

            foreach (SftpFile file in files)
            {
                if ((file.Name != ".") && (file.Name != ".."))
                {
                    string sourceFilePath = file.Name;
                    string destFilePath   = Path.Combine(destLocalPath, file.Name);
                    if (file.IsRegularFile)
                    {
                        using (Stream fileStream = File.Create(destFilePath))
                        {
                            sftpClient.DownloadFile(sourceFilePath, fileStream);
                            NewFiles.Add(file);
                        }
                    }
                }
            }

            return(NewFiles);
        }
        public byte[] obtenerArchivo(string directorioRemoto, string directorioLocal, string nombreArchivo, string login)
        {
            try
            {
                using (SftpClient sftp = new SftpClient(this._URI, this._Usuario, this._Password))
                {
                    sftp.Connect();
                    bool exists = System.IO.Directory.Exists(directorioLocal);

                    if (!exists)
                        System.IO.Directory.CreateDirectory(directorioLocal);

                    string fullLocalPath = directorioLocal + "\\(" + login + ")" + nombreArchivo;

                    using (Stream fileStream = File.Create(@fullLocalPath))
                    {
                        sftp.DownloadFile(directorioRemoto + "/" + nombreArchivo, fileStream);
                        fileStream.Close();
                    }
                    byte[] fileBytes = System.IO.File.ReadAllBytes(fullLocalPath);
                    return fileBytes;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Beispiel #16
0
        /// <summary>
        /// This sample will download a file on the remote system to your local machine.
        /// </summary>
        public static void DownloadFile(string localFile, string host, string username, string password)
        {
            try
            {
                Console.WriteLine("Enter local filename: ");
                localFile = "\\" + Console.ReadLine();
                localFile = Convert.ToString(Directory.GetCurrentDirectory() + localFile);
                // Delete the file if it exists.
                if (File.Exists(localFile))
                {
                    File.Delete(localFile);
                }

                //Create a file to write to.

                string localFileName = System.IO.Path.GetFileName(localFile);
                Console.WriteLine("Enter sftp filename: ");
                string remoteFileName = Console.ReadLine();

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

                    using (var file = File.OpenWrite(localFile))
                    {
                        sftp.DownloadFile(remoteFileName, file);
                    }

                    sftp.Disconnect();
                    sftp.Dispose();
                }
            }
            catch { }
        }
Beispiel #17
0
        private void DownloadFiles(string remoteFile, string localPath)
        {
            /// Try catch blocked so as to catch exception inside "Execute()"
            // var files = UnixFTPClient.ListDirectory(remoteDirectory);
            //try
            {
                var filename = "";

                if (File.Exists(localPath))
                {
                    File.Delete(localPath);
                    filename = localPath;
                }
                else if (!IsDir(localPath))
                {
                    filename = localPath;
                }
                else
                {
                    filename = localPath + @"\" + Path.GetFileName(remoteFile);
                }

                using (var f = File.OpenWrite(filename))
                {
                    UnixFTPClient.DownloadFile(remoteFile, f);
                }
            }
            //catch (Exception e)
            //{
            //    Reporter.ToLog(eLogLevel.ERROR, e.Message);
            // }
        }
Beispiel #18
0
        public ActionResult GetAll()
        {
            string result = "";

            using (var client = new SftpClient(host, port, username, password))
            {
                client.Connect();
                result = client.ConnectionInfo.ServerVersion;

                var files = client.ListDirectory("/folder/Test/inbounds/");
                foreach (var file in files)
                {
                    if (!file.Name.StartsWith("."))
                    {
                        string remoteFileName = file.Name;
                        var    filePath       = Path.Combine(@"c:\Project\testing2\", remoteFileName);
                        Stream stream         = System.IO.File.Create(filePath);

                        client.DownloadFile("/folder/Test/inbounds/" + remoteFileName, stream);
                        stream.Close();
                    }
                }
            }
            return(Ok(result));
        }
Beispiel #19
0
        private static void SFTP()
        {
            String Host                     = "test.rebex.net";
            int    Port                     = 22;
            String RemoteFileName           = "FluentFTP.dll";
            String LocalDestinationFilename = "readme666.txt";
            String Username                 = "******";
            String Password                 = "******";

            using (var sftp = new SftpClient(Host, Port, Username, Password))
            {
                sftp.Connect();

                //var files = sftp.ListDirectory("//");

                //foreach (var file in files)
                //{
                //    Console.WriteLine(file.Name);
                //}

                //using (var file = File.OpenRead(LocalDestinationFilename))
                //{
                //    sftp.UploadFile(file, RemoteFileName);
                //}



                using (var file = File.OpenWrite(LocalDestinationFilename))
                {
                    sftp.DownloadFile("readme.txt", file);
                }

                sftp.Disconnect();
            }
        }
Beispiel #20
0
        static void Main(string[] args)
        {
            // 必要な情報を設定する
            var host            = "<HostName>";
            var userName        = "******";
            var passPhrase      = "<PassPhrase>";
            var keyFilePath     = @"<Private Key File Path>";
            var sendFilePath    = @"<Send File Path>";
            var reseiveFilePath = @"<Save File Path>";

            // 認証メソッドを作成
            var authMethod = new PrivateKeyAuthenticationMethod(userName, new PrivateKeyFile(keyFilePath, passPhrase));

            // 接続情報を作成
            var connectionInfo = new ConnectionInfo(host, userName, authMethod);

            // SFTP クライアントを作成
            var client = new SftpClient(connectionInfo);

            // 接続。失敗した場合は例外が発生
            client.Connect();

            // ファイルのアップロード(上書き)
            using var sendStream = File.OpenRead(sendFilePath);
            client.UploadFile(sendStream, Path.GetFileName(sendFilePath), true);

            // ファイルのダウンロード(上書き)
            using var reseiveStream = File.OpenWrite(reseiveFilePath);
            client.DownloadFile(Path.GetFileName(sendFilePath), reseiveStream);

            // 切断
            client.Disconnect();
        }
Beispiel #21
0
        void DownLoadJsonFile()
        {
            if (ServerList.selected_serverinfo_textblock.serverinfo == null)
            {
                return;
            }

            string     ip       = ServerList.selected_serverinfo_textblock.serverinfo.ip;
            string     id       = ServerList.selected_serverinfo_textblock.serverinfo.id;
            string     password = ServerList.selected_serverinfo_textblock.serverinfo.password;
            SftpClient sftp     = new SftpClient(ip, id, password);

            sftp.Connect();

            string local_directory  = AppDomain.CurrentDomain.BaseDirectory;
            string remote_directory = "/home/cofile/bin/";
            var    files            = sftp.ListDirectory(remote_directory);

            foreach (var file in files)
            {
                if (file.Name.Length > 4 && file.Name.Substring(file.Name.Length - 5) == ".json")
                {
                    FileStream fs = new FileStream(local_directory + file.Name, FileMode.Create);
                    sftp.DownloadFile(remote_directory + file.Name, fs);
                    Console.WriteLine("[ download ] " + file.Name);
                }
            }
        }
Beispiel #22
0
 private static void download_file_sftp(SftpClient client, SftpFile file, string directory)
 {
     using (Stream fileStream = File.OpenWrite(System.IO.Path.Combine(directory, file.Name)))
     {
         client.DownloadFile(file.FullName, fileStream);
     }
 }
Beispiel #23
0
 /// <summary>
 /// Downloads file from the SFTP server.
 /// Defaulted to downloads on user's computer.
 /// </summary>
 /// <param name="sftpClient"></param>
 /// <param name="fileName"></param>
 private static void DownloadFile(SftpClient sftpClient, string serverFile, string fileToDownload)
 {
     using (Stream stream = File.OpenWrite(fileToDownload))
     {
         sftpClient.DownloadFile(serverFile, stream, x => { Console.WriteLine("\nSuccessfully Downloaded!"); });
     }
 }
Beispiel #24
0
        private void downloadWithSFTP(string fileName)
        {
            string host     = parts[1];
            string port     = parts[2];
            string username = parts[3];

            try
            {
                using (Stream stream = new FileStream(getDownloadFolderPath() + @"\" + fileName, FileMode.Create))
                    using (var sftp = new SftpClient(host, Convert.ToInt32(port), username, PasswordTBDownload.Text.ToString()))
                    {
                        sftp.Connect();
                        SftpFileAttributes attributes = sftp.GetAttributes("./" + fileName);
                        var files = sftp.ListDirectory("./");
                        progressBar1.Invoke(
                            (MethodInvoker) delegate { progressBar1.Maximum = (int)attributes.Size; });
                        sftp.DownloadFile(fileName, stream, UpdateProgressBar);
                        MessageBox.Show("Download Complete");

                        sftp.Disconnect();
                        sftp.Dispose();
                    }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "Αn Εrror Οccurred", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        public Attempt <byte[]> GetFile(XElement config, string relativePath)
        {
            var result = Attempt.Fail <byte[]>();

            try
            {
                var settings       = LoadSettings(config);
                var connectionInfo = new ConnectionInfo(settings.Server, settings.Username, new PasswordAuthenticationMethod(settings.Username, settings.Password), new PrivateKeyAuthenticationMethod("rsa.key"));

                using (SftpClient sftpClient = new SftpClient(connectionInfo))
                {
                    sftpClient.Connect();

                    using (var ms = new MemoryStream())
                    {
                        sftpClient.DownloadFile(Path.Combine(settings.Folder, relativePath).Replace('\\', '/'), ms);
                        result = Attempt.Succeed(ms.ToArray());
                    }

                    sftpClient.Disconnect();
                }
            }
            catch (Exception ex)
            {
                result = Attempt.Fail <byte[]>(null, ex);
            }

            return(result);
        }
Beispiel #26
0
        /// <summary>
        /// 파일명 지정해서 download
        /// </summary>
        /// <param name="remoteFileName"></param>
        public void DownloadFile(string remoteFileName, string localdir)
        {
            string host     = @"13.209.113.71";
            string username = "******";

            pathLocalGet = localdir;
            if (!Directory.Exists(pathLocalGet))
            {
                Directory.CreateDirectory(pathLocalGet);
            }


            string pathRemote         = "/ftp/bnk_b/downloads/";
            string pathRemoteSendDone = "/ftp/bnk_b/downloads/send_done/";

            string pathRemoteFile         = Path.Combine(pathRemote, remoteFileName);
            string pathRemoteSendDoneFile = Path.Combine(pathRemoteSendDone, remoteFileName);
            string pathLocalFile          = Path.Combine(pathLocalGet, remoteFileName);


            PrivateKeyFile keyFile  = new PrivateKeyFile(@"./bnk_sftp.pem");
            var            keyFiles = new[] { keyFile };

            var methods = new List <AuthenticationMethod>();

            methods.Add(new PrivateKeyAuthenticationMethod(username, keyFiles));

            ConnectionInfo con = new ConnectionInfo(host, 10021, username, methods.ToArray());

            using (SftpClient sftp = new SftpClient(con))
            {
                try
                {
                    sftp.Connect();

                    if (sftp.Exists(pathRemoteFile))
                    {
                        File.Delete(pathLocalFile);

                        using (Stream fileStream = File.OpenWrite(pathLocalFile))
                        {
                            Console.WriteLine("Downloading {0}", pathRemoteFile);

                            sftp.DownloadFile(pathRemoteFile, fileStream);
                            sftp.RenameFile(pathRemoteFile, BuildRemoteSendDoneFileName(pathRemoteSendDoneFile));
                        }
                    }
                    else
                    {
                        Console.WriteLine("File not found skip {0}", pathRemoteFile);
                    }

                    sftp.Disconnect();
                }
                catch (Exception er)
                {
                    Console.WriteLine("An exception has been caught " + er.ToString());
                }
            }
        }
Beispiel #27
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);
                }
            }
        }
Beispiel #28
0
        private async Task <DownLoadedFileModel> DownLoadAFileProcessAsync(SftpFile file, SftpClient sftp, string SavedPath, SemaphoreSlim SemaphoreForRecord)
        {
            /// if an exception occurred, the LocalPath is null and ExceptionMessage has value in DownLoadFileModel.
            return(await Task.Run(() =>
            {
                DownLoadedFileModel rslt = new DownLoadedFileModel
                {
                    FtpPath = file.FullName,
                    LocalPath = $"{SavedPath}\\{Path.GetFileName(file.FullName)}",
                };

                SemaphoreForRecord.Wait();
                try
                {
                    using (FileStream wrt = new FileStream(rslt.LocalPath, FileMode.Create, FileAccess.ReadWrite))
                    {
                        sftp.DownloadFile(file.FullName, wrt);
                        wrt.Flush();
                    }
                }
                catch (Exception ex)
                {
                    rslt.LocalPath = null;
                    rslt.ExceptionMessage = ex.Message;
                }
                finally
                {
                    SemaphoreForRecord.Release();
                }
                return rslt;
            }));
        }
Beispiel #29
0
        // TODO: FTP exception or NULL file exception
        public void download(string serverpath, string clientpath, bool createdir = true)
        {
            using (SftpClient client = new SftpClient(Server.IPv4, Convert.ToInt32(Server.Port), Server.User, Server.Password))
            {
                client.ConnectionInfo.Timeout = new TimeSpan(Server.Timeout * 10000);
                client.Connect();
                for (int retry = 0; retry < MAX_RETRY; retry++)
                {
                    try
                    {
                        if (createdir)
                        {
                            Directory.CreateDirectory(Path.GetDirectoryName(clientpath));
                        }

                        // response stream
                        using (Stream filestream = File.Create(clientpath))
                        {
                            client.DownloadFile(serverpath, filestream);
                        }

                        break;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(@"sftp error:" + ex.Message);
                        Thread.Sleep(1000);
                        continue;
                    }
                }
                client.Disconnect();
            }
        }
Beispiel #30
0
        public List <string> Receive(TargetTransformData sourceData, string targetPath, string regex)
        {
            List <string> result     = new List <string>();
            string        host       = sourceData.IpAddress;
            string        userName   = sourceData.Login;
            string        password   = sourceData.Password;
            string        sourcePath = sourceData.Path;
            string        localPath  = targetPath;

            WildcardPattern wildCard = new WildcardPattern(regex);

            using (var sftp = new SftpClient(host, userName, password))
            {
                sftp.Connect();
                var files = sftp.ListDirectory(sourcePath);
                foreach (var file in files)
                {
                    string fileName = file.Name;
                    if (wildCard.IsMatch(fileName))
                    {
                        Stream file1 = File.OpenRead(localPath);
                        sftp.DownloadFile(file.FullName, file1);
                        result.Add(localPath + file.Name);
                    }
                }
            }
            return(result);
        }
        public void Test_Sftp_Download_File_Not_Exists()
        {
            using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                sftp.Connect();

                string remoteFileName = "/xxx/eee/yyy";
                using (var ms = new MemoryStream())
                {
                    sftp.DownloadFile(remoteFileName, ms);
                }

                sftp.Disconnect();
            }
        }
        public void Test_Sftp_Download_Forbidden()
        {
            if (Resources.USERNAME == "root")
                Assert.Fail("Must not run this test as root!");

            using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                sftp.Connect();

                string remoteFileName = "/root/.profile";

                using (var ms = new MemoryStream())
                {
                    sftp.DownloadFile(remoteFileName, ms);
                }

                sftp.Disconnect();
            }
        }
        public void Test_Sftp_Upload_And_Download_1MB_File()
        {
            RemoveAllFiles();

            using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                sftp.Connect();

                string uploadedFileName = Path.GetTempFileName();
                string remoteFileName = Path.GetRandomFileName();

                this.CreateTestFile(uploadedFileName, 1);

                //  Calculate has value
                var uploadedHash = CalculateMD5(uploadedFileName);

                using (var file = File.OpenRead(uploadedFileName))
                {
                    sftp.UploadFile(file, remoteFileName);
                }

                string downloadedFileName = Path.GetTempFileName();

                using (var file = File.OpenWrite(downloadedFileName))
                {
                    sftp.DownloadFile(remoteFileName, file);
                }

                var downloadedHash = CalculateMD5(downloadedFileName);

                sftp.DeleteFile(remoteFileName);

                File.Delete(uploadedFileName);
                File.Delete(downloadedFileName);

                sftp.Disconnect();

                Assert.AreEqual(uploadedHash, downloadedHash);
            }
        }
Beispiel #34
0
            // get file from SFTP and return string
            public void getFromSFTP(string hostname, int port, string userName, string password, string tempFileName, string fileName)
            {
            try
            {
                mySFTPClient = new SftpClient(hostname, port, userName, password);
                myFileStream = new FileStream(tempFileName, FileMode.Create);

                mySFTPClient.Connect();
                mySFTPClient.DownloadFile(fileName, myFileStream, DownloadDone); // DownloadDone is Action<ulong>

                return;
            }
            catch (Exception e)
            {
                CrestronConsole.PrintLine("Document.getFromSFTP() Exception {0}", e);
                CrestronConsole.PrintLine("Document.getFromSFTP() Host {0}, Port {1}, User {2}, fileName {3}",
                                            hostname, port, userName, fileName);
                throw;
            }
            finally
            {
                mySFTPClient.Disconnect();
                myFileStream.Close();
            }
            }
Beispiel #35
0
        // get file from SFTP and return string
        public void getFromSFTP(string url)
        {
            try
            {
                myFileStream = new FileStream(@"\NVRAM\temp.txt", FileMode.Create);
                mySFTPClient = new SftpClient(url, 22, "Crestron", "");

                mySFTPClient.Connect();
                mySFTPClient.DownloadFile(url, myFileStream, DownloadDone);

                return;
            }
            catch (Exception e)
            {
                CrestronConsole.PrintLine("Exception {0}", e);
                return;
            }
            finally
            {
                mySFTPClient.Disconnect();
                myFileStream.Close();
            }
        }
Beispiel #36
0
            public ushort OpenSFTPFile(String strUser, String strPassword, String strHost, String strPath)
            {
                ushort returnvalue = 1;
                FileStream myStream;
                SftpClient myClient;
                try
                {
                    myStream = new FileStream(@"\nvram\temp.txt", FileMode.Create);
                    myClient = new SftpClient(strHost, 22, strUser, strPassword);
                    myClient.Connect();
                    //Action<ulong> myAction = DownloadDone; // Defines that myAction is a delegate that takes a single ulong input and is the same as the function download done.
                    myClient.DownloadFile(strPath, myStream, DownloadDone); // Replace DownloadDone with myAction if using.
                    myClient.Disconnect();
                    myStream.Close();
                }
                catch (Exception e)
                {
                    ErrorLog.Error(String.Format("Error Loading SFTP file: {0}", e.Message));
                    returnvalue = 0;
                }
                finally
                {
                    if (returnvalue == 1)
                        OpenLocalFile(@"\nvram\temp.txt");
                }

                return returnvalue;
            }
Beispiel #37
0
 public void DownloadFileTest()
 {
     ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
     SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
     string path = string.Empty; // TODO: Initialize to an appropriate value
     Stream output = null; // TODO: Initialize to an appropriate value
     Action<ulong> downloadCallback = null; // TODO: Initialize to an appropriate value
     target.DownloadFile(path, output, downloadCallback);
     Assert.Inconclusive("A method that does not return a value cannot be verified.");
 }