async Task IFtpSession.UploadAsync(string localPath, string remotePath, bool overwrite, bool recursive, CancellationToken cancellationToken) { if (string.IsNullOrWhiteSpace(localPath)) { throw new ArgumentNullException(nameof(localPath)); } if (string.IsNullOrWhiteSpace(remotePath)) { throw new ArgumentNullException(nameof(remotePath)); } if (cancellationToken == null) { throw new ArgumentNullException(nameof(cancellationToken)); } if (Directory.Exists(localPath)) { IEnumerable <Tuple <string, string> > listing = GetLocalListing(localPath, remotePath, recursive); foreach (Tuple <string, string> pair in listing) { cancellationToken.ThrowIfCancellationRequested(); string directoryPath = FtpConfiguration.GetDirectoryPath(pair.Item2); if (!_sftpClient.Exists(directoryPath)) { _sftpClient.CreateDirectory(directoryPath); } using (Stream fileStream = File.OpenRead(pair.Item1)) { await Task.Factory.FromAsync(_sftpClient.BeginUploadFile(fileStream, pair.Item2, overwrite, null, null), _sftpClient.EndUploadFile); } } } else { if (File.Exists(localPath)) { if (_sftpClient.Exists(remotePath) && !overwrite) { throw new IOException(Resources.FileExistsException); } using (Stream fileStream = File.OpenRead(localPath)) { await Task.Factory.FromAsync(_sftpClient.BeginUploadFile(fileStream, remotePath, overwrite, null, null), _sftpClient.EndUploadFile); } } else { throw new ArgumentException(string.Format(Resources.PathNotFoundException, localPath), nameof(localPath)); } } }
public void Upload() { if (Protocol == SSHTransferProtocol.SCP) { if (!ScpClt.IsConnected) { //Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg, // Language.strSSHTransferFailed + Environment.NewLine + // "SCP Not Connected!"); return; } ScpClt.Upload(new FileInfo(SrcFile), $"{DstFile}"); } if (Protocol == SSHTransferProtocol.SFTP) { if (!SftpClt.IsConnected) { //Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg, // Language.strSSHTransferFailed + Environment.NewLine + // "SFTP Not Connected!"); return; } stream_upload = new FileStream(SrcFile, Open); async_upload_result = (SftpUploadAsyncResult)SftpClt.BeginUploadFile(stream_upload, $"{DstFile}", asyncCallback); } }
public async Task UploadFileAsync(string pathfile, string file, string error) { using (Stream stream = File.OpenRead(pathfile)) { try { //long totaluploaded = 0; //var task = client.BeginUploadFile(stream, file) as SftpUploadAsyncResult; //while (!task.IsCompleted) //{ // SetProgressStatus(totaluploaded + (long)task.UploadedBytes, stream.Length,file); //} //client.EndUploadFile(task); //totaluploaded += stream.Length; // ko dung var task = Task.Factory.FromAsync(client.BeginUploadFile(stream, file), client.EndUploadFile); demFileSuccess++; progressBar1.Invoke(new MethodInvoker(delegate() { progressBar1.Value = ((demFileSuccess - 1) * 100 / Files.Count()); })); SuccessFile(Files.Count()); WriteLog(file + " done"); await task; } catch (Exception ex) { demFileError++; ErrorFile(); WriteLogToTxt(error, file + " error: " + ex.ToString()); } } }
public async Task CopyFile(string fromPath, string toPath) { if (!_connected) { throw new InvalidOperationException("SSH not connected"); } if (string.IsNullOrEmpty(fromPath) || string.IsNullOrEmpty(toPath)) { throw new InvalidOperationException("Invalid operation: please provide correct paths"); } if (_sfClient.Exists(toPath)) { ConsoleWriter.Error($"Removing existing docker compose file @ [ {toPath} ]"); _sfClient.DeleteFile(toPath); } using (var fileStream = new FileStream(fromPath, FileMode.Open, FileAccess.Read)) { ConsoleWriter.Warning($"Creating new docker compose file @ [ {toPath} ]"); var _result = _sfClient.BeginUploadFile(fileStream, toPath); while (!_result.IsCompleted) { await Task.Delay(1000); } ConsoleWriter.Warning($"Docker compose file created @ [ {toPath} ]"); } }
protected override async Task PerformIO() { bool hadToConnect = _client.ConnectIfNeeded(); _client.CreateDirectoriesIfNeeded(Folder); string fullFilePath = ODFileUtils.CombinePaths(Folder, FileName, '/'); using (MemoryStream uploadStream = new MemoryStream(FileContent)) { SftpUploadAsyncResult res = (SftpUploadAsyncResult)_client.BeginUploadFile(uploadStream, fullFilePath); while (!res.AsyncWaitHandle.WaitOne(100)) { if (DoCancel) { res.IsUploadCanceled = true; } OnProgress((double)res.UploadedBytes / (double)1024 / (double)1024, "?currentVal MB of ?maxVal MB uploaded", (double)FileContent.Length / (double)1024 / (double)1024, ""); } _client.EndUploadFile(res); if (res.IsUploadCanceled) { TaskStateDelete state = new Delete() { _client = this._client, Path = fullFilePath }; state.Execute(false); } } _client.DisconnectIfNeeded(hadToConnect); await Task.Run(() => { }); //Gets rid of a compiler warning and does nothing. }
public void UploadData(Stream stream, string fileName) { Connect(); progress = new ProgressManager(stream.Length); ChangeDirectory(FTPAccount.GetSubFolderPath()); object s = new object(); AsyncCallback ac = new AsyncCallback(CallBack); var result = client.BeginUploadFile(stream, Path.GetFileName(fileName), ac, s); SftpUploadAsyncResult sftpresult = result as SftpUploadAsyncResult; while (!sftpresult.IsCompleted) { if (sftpresult.UploadedBytes > 0) { OnTransferProgressChanged(sftpresult); } Thread.Sleep(500); } Disconnect(); }
private static void UploadFiles(string address, List <FileInfo> files) { var client = new SftpClient(address, 22, User, Password); client.Connect(); client.BufferSize = 4 * 1024; if (!client.Exists("/home/ec2-user/socialwargames/")) { client.CreateDirectory("/home/ec2-user/socialwargames/"); } List <Task> tasks = new List <Task>(); var count = 0; for (var index = 0; index < files.Count; index++) { var fileInfo = files[index]; tasks.Add(Task.Factory.FromAsync((callback, stateObject) => { // Console.WriteLine($"{fileInfo.Name} {index}/{files.Count}"); return(client.BeginUploadFile(fileInfo.OpenRead(), "/home/ec2-user/socialwargames/" + fileInfo.Name, true, callback, stateObject)); }, (result) => { count++; Console.WriteLine($"{address} {count}/{files.Count}"); client.EndUploadFile(result); }, null)); } Task.WaitAll(tasks.ToArray()); client.Disconnect(); client.Dispose(); }
/// <summary> /// Upload method using SSH.NET SFTP implementation for async files uploading. /// </summary> private void UPLOAD(SftpClient client, String localFileName) { string name = localFileName; int pos = name.LastIndexOf(@"\") + 1; String remoteFileName = name.Substring(pos, name.Length - pos); Modify_UploadStatusTextBox(UploadStatusTextBox, System.Environment.NewLine + "Checking if local file " + localFileName + " exists..." + System.Environment.NewLine); if (File.Exists(localFileName)) { Console.WriteLine("Local file exists, continue..."); Modify_UploadStatusTextBox(UploadStatusTextBox, "File exists..." + System.Environment.NewLine); localFileSize = new FileInfo(localFileName).Length; Console.WriteLine("File size is: " + localFileSize); Modify_UploadStatusTextBox(UploadStatusTextBox, "File size is: " + localFileSize + "." + System.Environment.NewLine); using (Stream file = File.OpenRead(localFileName)) { Modify_UploadStatusTextBox(UploadStatusTextBox, "Uploading file " + localFileName + " ..." + System.Environment.NewLine); Console.WriteLine("### CLIENT: " + client); Console.WriteLine("## FILE: " + file); IAsyncResult asyncr = client.BeginUploadFile(file, remoteFileName); sftpAsyncrUpload = (SftpUploadAsyncResult)asyncr; while (!sftpAsyncrUpload.IsCompleted && !sftpAsyncrUpload.IsUploadCanceled) { int pct = Convert.ToInt32(((double)sftpAsyncrUpload.UploadedBytes / (double)localFileSize) * 100); double temp = (double)sftpAsyncrUpload.UploadedBytes / (double)localFileSize; Console.WriteLine("Uploaded Bytes: " + sftpAsyncrUpload.UploadedBytes); Console.WriteLine("Uploaded: " + temp); Console.WriteLine("File size is: " + localFileSize); Console.WriteLine(pct); Modify_progressBar2(progressBar2, pct); Modify_UploadLabel(UploadLabel, "Status: " + pct + " %"); Modify_UploadBytesLabel(UploadBytesLabel, sftpAsyncrUpload.UploadedBytes); } client.EndUploadFile(asyncr); file.Close(); } if (sftpAsyncrUpload.IsUploadCanceled) { Console.WriteLine("File Upload has been canceled!"); Modify_UploadStatusTextBox(UploadStatusTextBox, "File Upload has been canceled!" + System.Environment.NewLine); } else { Console.WriteLine("The file " + localFileName + " has been successfully uploaded successfully to the server!"); Modify_UploadStatusTextBox(UploadStatusTextBox, "The file " + localFileName + " has been uploaded successfully!" + System.Environment.NewLine); } } else { MessageBox.Show("The file " + localFileName + " does not exists on this computer", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public IAsyncResult BeginUploadFile(Stream stream, string path, AsyncCallback callback, Action <ulong> progress) { ColoredConsole.WriteLine(ConsoleColor.Cyan, "SSH.NET: Beginning upload of file {0}...", path); var ar = _connection.BeginUploadFile(stream, path, callback, progress); ColoredConsole.WriteLine(ConsoleColor.Green, "SSH.NET: File {0} is being uploaded.", path); return(ar); }
public void Test_Sftp_BeginUploadFile_FileNameIsWhiteSpace() { using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { sftp.Connect(); sftp.BeginUploadFile(new MemoryStream(), " ", null, null); sftp.Disconnect(); } }
public void Test_Sftp_BeginUploadFile_StreamIsNull() { using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { sftp.Connect(); sftp.BeginUploadFile(null, "aaaaa", null, null); sftp.Disconnect(); } }
public void Test_Sftp_BeginUploadFile_FileNameIsNull() { using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { sftp.Connect(); sftp.BeginUploadFile(new MemoryStream(), null, null, null); sftp.Disconnect(); } }
public static Task UploadAsync(this SftpClient client, Stream input, string path, Action <ulong> uploadCallback = null, TaskFactory factory = null, TaskCreationOptions creationOptions = default(TaskCreationOptions), TaskScheduler scheduler = null) { return((factory = factory ?? Task.Factory).FromAsync( client.BeginUploadFile(input, path, null, null, uploadCallback), client.EndUploadFile, creationOptions, scheduler ?? factory.Scheduler ?? TaskScheduler.Current)); }
public void Test_Sftp_EndUploadFile_Invalid_Async_Handle() { using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { sftp.Connect(); var async1 = sftp.BeginListDirectory("/", null, null); var filename = Path.GetTempFileName(); this.CreateTestFile(filename, 100); var async2 = sftp.BeginUploadFile(File.OpenRead(filename), "test", null, null); sftp.EndUploadFile(async1); } }
/// <summary> /// Upload a file via SFTP. /// </summary> /// <param name="file">The file to upload.</param> /// <returns>True on failure, false on success.</returns> static bool UploadSftp(UploadFile file) { try { SftpClient client; if (Settings.Default.TransferType == (int)TransferType.SftpKeys) { client = new SftpClient(Settings.Default.Host, Settings.Default.Port, Settings.Default.Username, new PrivateKeyFile(Misc.Decrypt(Settings.Default.Password))); } else { client = new SftpClient(Settings.Default.Host, Settings.Default.Port, Settings.Default.Username, Misc.Decrypt(Settings.Default.Password)); } using (FileStream inputStream = new FileStream(file.Path, FileMode.Open)) using (SftpClient outputStream = client) { outputStream.Connect(); if (!String.IsNullOrEmpty(Settings.Default.Directory)) { outputStream.ChangeDirectory(Settings.Default.Directory); } IAsyncResult async = outputStream.BeginUploadFile(inputStream, file.FileName); SftpUploadAsyncResult sftpAsync = async as SftpUploadAsyncResult; while (sftpAsync != null && !sftpAsync.IsCompleted) { if (UploadWorker.CancellationPending) { return(true); } UploadWorker.ReportProgress((int)(sftpAsync.UploadedBytes * 100 / (ulong)inputStream.Length)); } outputStream.EndUploadFile(async); } return(false); } catch (Exception e) { _uploadStatus = Misc.HandleErrorStatusText(Resources.Sftp); Misc.HandleError(e, Resources.Sftp); return(true); } }
private static async Task UploadFiles(string timestamp, string outputPath, string rsaPrivate, string sftpHost, string sftpUsername) { using var client = new SftpClient(sftpHost, sftpUsername, new PrivateKeyFile(File.OpenRead(rsaPrivate))) { BufferSize = 4096, OperationTimeout = TimeSpan.FromHours(1), }; client.Connect(); client.CreateDirectory(timestamp); foreach (var file in Directory.GetFiles(outputPath)) { using var zipUpload = File.OpenRead(file); await Task.Factory.FromAsync((callback, stateObject) => client.BeginUploadFile(zipUpload, $"{timestamp}\\{Path.GetFileName(file)}", callback, stateObject), result => client.EndUploadFile(result), null); } client.Disconnect(); }
public static void UploadFile(FileInfo file, string ftpDir) { log.WriteLine("\nAttempting to upload " + file.FullName + " to " + ftpDir + "/" + file.Name + "... ", false); Run("touch " + ftpDir + "/" + file.Name); var inputStream = file.OpenRead(); var up = sftp.BeginUploadFile(inputStream, ftpDir + "/" + file.Name); while (!up.IsCompleted) { ; } sftp.EndUploadFile(up); inputStream.Close(); log.WriteLine("Sucess!", false); }
private static void UploadFileToSFTP(IEnumerable <string> filePaths) { try { using var client = new SftpClient(_host, _port, _user, _password); client.Connect(); var i = client.ConnectionInfo; if (client.IsConnected) { Console.WriteLine($"Conectado a: {i.Host}"); if (_log) { Logger.Logger.i($"Conectado a: {i.Host}"); } foreach (var filePath in filePaths) { using var fileStream = new FileStream(filePath, FileMode.Open); client.BeginUploadFile(fileStream, Path.GetFileName(filePath), null, null); Console.WriteLine("Archivo enviado: {0} ({1:N0} bytes)", filePath, fileStream.Length); if (_log) { Logger.Logger.i($"Archivo enviado: {filePath}"); } client.BufferSize = 4 * 1024; // bypass Payload error large files client.UploadFile(fileStream, Path.GetFileName(filePath)); } client.Disconnect(); Console.WriteLine($"Desconectado de: {i.Host}"); if (_log) { Logger.Logger.i($"Desconectado de: {i.Host}"); } } else { Debug.WriteLine("No se pudo conectar al cliente."); } } catch (Exception e) { Console.WriteLine(e); throw; } }
/// <summary> /// Upload the specified file /// </summary> /// <param name="settings">ftp server settings</param> /// <param name="fileName">Name of the file on ftp server</param> /// <param name="fullFileName">Name of the file, inclusive path, of the file</param> /// <returns></returns> public async Task <bool> UploadAsync(FTPSettings settings, string fileName, string fullFileName) { var connectionInfo = CreateConnectionInfo(settings); using (var sftp = new SftpClient(connectionInfo)) { sftp.Connect(); ChangeServerPath(sftp, settings.ServerPath); using (var fileStream = File.OpenRead(fullFileName)) { await Task.Factory.FromAsync(sftp.BeginUploadFile(fileStream, fileName, true, (IAsyncResult result) => { }, null), sftp.EndUploadFile); } sftp.Disconnect(); } return(true); }
public async Task <bool> SaveFileAsync(string path, Stream stream, CancellationToken cancellationToken = default) { if (String.IsNullOrEmpty(path)) { throw new ArgumentNullException(nameof(path)); } if (stream == null) { throw new ArgumentNullException(nameof(stream)); } path = NormalizePath(path); EnsureClientConnected(); EnsureDirectoryExists(path); await Task.Factory.FromAsync(_client.BeginUploadFile(stream, path, null, null), _client.EndUploadFile).AnyContext(); return(true); }
/// <summary> /// Uploads the given <paramref name="inputStream"/> to the given <paramref name="path"/> asynchronously. /// </summary> /// <param name="client">The SFTP client to perform the upload action with.</param> /// <param name="path">The path to where the file should be uploaded to.</param> /// <param name="inputStream">The input stream containing the data to upload.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns> /// <exception cref="ArgumentNullException">If <paramref name="client"/> or <paramref name="inputStream"/> is null.</exception> /// <exception cref="ArgumentException">If <paramref name="path"/> is null or white space.</exception> public static Task UploadFileAsync(this SftpClient client, string path, Stream inputStream, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); if (client == null) { throw new ArgumentNullException(nameof(client)); } if (inputStream == null) { throw new ArgumentNullException(nameof(inputStream)); } if (string.IsNullOrWhiteSpace(path)) { throw new ArgumentException("Path must not be null or white space."); } cancellationToken.ThrowIfCancellationRequested(); return(Task.Factory.FromAsync(client.BeginUploadFile(inputStream, path), result => client.EndUploadFile(result))); }
/// <summary> /// Upload the captured image, file path found in CapturedImage.LocalPath /// </summary> public static void UploadCapturedImage() { if (FTP) { ftpc.PutFileAsync(CapturedImage.LocalPath, CapturedImage.RemotePath, FileAction.CreateNew); } else { EventWaitHandle wait = new AutoResetEvent(false); using (var file = File.OpenRead(CapturedImage.LocalPath)) { var asynch = sftpc.BeginUploadFile(file, CapturedImage.RemotePath, delegate { Console.Write("\nCallback called."); wait.Set(); }, null); var sftpASynch = asynch as Renci.SshNet.Sftp.SftpUploadAsyncResult; while (!sftpASynch.IsCompleted) { if (sftpASynch.UploadedBytes > 0) { Console.Write("\rUploaded {0} bytes ", sftpASynch.UploadedBytes); } Thread.Sleep(100); } Console.Write("\rUploaded {0} bytes!", sftpASynch.UploadedBytes); sftpc.EndUploadFile(asynch); wait.WaitOne(); } CaptureControl.ImageUploaded(); } }
public void UploadFile(SftpClient client, string filepath, string name, UploadType type) { using (FileStream fs = new FileStream(filepath, FileMode.Open)) { var result = client.BeginUploadFile(fs, name) as SftpUploadAsyncResult; Main form = Main._myInstance; double fsLength = Convert.ToDouble(fs.Length); long sizeLimit = Properties.Settings.Default.SizeLimit; if (sizeLimit != 0 && fs.Length > sizeLimit) { return; } int lastStage = -1; while (!result.IsCompleted) { Thread.Sleep(100); double progress = (double)(Convert.ToDouble(result.UploadedBytes) / fsLength) * 100.0; form.setIconText("Uploading: \n" + Math.Round(progress) + "% - (" + Math.Round((result.UploadedBytes / 1000000.0), 2) + "MB/" + Math.Round((fsLength / 1000000.0), 2) + "MB)"); int rotationStage = (int)(progress / 25); if (rotationStage != lastStage) { lastStage = rotationStage; form.setIconRotation((int)(progress / 25)); } } string url = "http://" + type.getUrlPrefix() + "." + Properties.Settings.Default.Domain + "/" + name; System.Windows.Forms.Clipboard.SetText(url); System.Media.SoundPlayer player = new System.Media.SoundPlayer(Siqve_Uploader.Properties.Resources.decay); player.Play(); form.addLine(url); form.setIcon(); } }
private void StartTransfer(SSHTransferProtocol Protocol) { if (AllFieldsSet() == false) { Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg, Language.strPleaseFillAllFields); return; } if (File.Exists(this.txtLocalFile.Text) == false) { Runtime.MessageCollector.AddMessage(Messages.MessageClass.WarningMsg, Language.strLocalFileDoesNotExist); return; } try { if (Protocol == SSHTransferProtocol.SCP) { var ssh = new ScpClient(txtHost.Text, int.Parse(this.txtPort.Text), txtUser.Text, txtPassword.Text); ssh.Uploading+=(sender, e) => SetProgressStatus(e.Uploaded, e.Size); DisableButtons(); ssh.Connect(); ssh.Upload(new FileStream(txtLocalFile.Text,FileMode.Open), txtRemoteFile.Text); } else if (Protocol == SSHTransferProtocol.SFTP) { var ssh = new SftpClient(txtHost.Text, int.Parse(txtPort.Text),txtUser.Text, txtPassword.Text); var s = new FileStream(txtLocalFile.Text, FileMode.Open); ssh.Connect(); var i = ssh.BeginUploadFile(s, txtRemoteFile.Text) as SftpUploadAsyncResult; ThreadPool.QueueUserWorkItem(state => { while (!i.IsCompleted) { SetProgressStatus((long)i.UploadedBytes, s.Length); } MessageBox.Show(Language.SSHTransfer_StartTransfer_Upload_completed_); EnableButtons(); }); } } catch (Exception ex) { Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg, Language.strSSHTransferFailed + Constants.vbNewLine + ex.Message); EnableButtons(); } }
public void Test_Sftp_Multiple_Async_Upload_And_Download_10Files_5MB_Each() { var maxFiles = 10; var maxSize = 5; using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { sftp.Connect(); var testInfoList = new Dictionary<string, TestInfo>(); for (int i = 0; i < maxFiles; i++) { var testInfo = new TestInfo(); testInfo.UploadedFileName = Path.GetTempFileName(); testInfo.DownloadedFileName = Path.GetTempFileName(); testInfo.RemoteFileName = Path.GetRandomFileName(); this.CreateTestFile(testInfo.UploadedFileName, maxSize); // Calculate hash value testInfo.UploadedHash = CalculateMD5(testInfo.UploadedFileName); testInfoList.Add(testInfo.RemoteFileName, testInfo); } var uploadWaitHandles = new List<WaitHandle>(); // Start file uploads foreach (var remoteFile in testInfoList.Keys) { var testInfo = testInfoList[remoteFile]; testInfo.UploadedFile = File.OpenRead(testInfo.UploadedFileName); testInfo.UploadResult = sftp.BeginUploadFile(testInfo.UploadedFile, remoteFile, null, null) as SftpUploadAsyncResult; uploadWaitHandles.Add(testInfo.UploadResult.AsyncWaitHandle); } // Wait for upload to finish bool uploadCompleted = false; while (!uploadCompleted) { // Assume upload completed uploadCompleted = true; foreach (var testInfo in testInfoList.Values) { var sftpResult = testInfo.UploadResult; if (!testInfo.UploadResult.IsCompleted) { uploadCompleted = false; } } Thread.Sleep(500); } // End file uploads foreach (var remoteFile in testInfoList.Keys) { var testInfo = testInfoList[remoteFile]; sftp.EndUploadFile(testInfo.UploadResult); testInfo.UploadedFile.Dispose(); } // Start file downloads var downloadWaitHandles = new List<WaitHandle>(); foreach (var remoteFile in testInfoList.Keys) { var testInfo = testInfoList[remoteFile]; testInfo.DownloadedFile = File.OpenWrite(testInfo.DownloadedFileName); testInfo.DownloadResult = sftp.BeginDownloadFile(remoteFile, testInfo.DownloadedFile, null, null) as SftpDownloadAsyncResult; downloadWaitHandles.Add(testInfo.DownloadResult.AsyncWaitHandle); } // Wait for download to finish bool downloadCompleted = false; while (!downloadCompleted) { // Assume download completed downloadCompleted = true; foreach (var testInfo in testInfoList.Values) { var sftpResult = testInfo.DownloadResult; if (!testInfo.DownloadResult.IsCompleted) { downloadCompleted = false; } } Thread.Sleep(500); } var hashMatches = true; var uploadDownloadSizeOk = true; // End file downloads foreach (var remoteFile in testInfoList.Keys) { var testInfo = testInfoList[remoteFile]; sftp.EndDownloadFile(testInfo.DownloadResult); testInfo.DownloadedFile.Dispose(); testInfo.DownloadedHash = CalculateMD5(testInfo.DownloadedFileName); if (!(testInfo.UploadResult.UploadedBytes > 0 && testInfo.DownloadResult.DownloadedBytes > 0 && testInfo.DownloadResult.DownloadedBytes == testInfo.UploadResult.UploadedBytes)) { uploadDownloadSizeOk = false; } if (!testInfo.DownloadedHash.Equals(testInfo.UploadedHash)) { hashMatches = false; } } // Clean up after test foreach (var remoteFile in testInfoList.Keys) { var testInfo = testInfoList[remoteFile]; sftp.DeleteFile(remoteFile); File.Delete(testInfo.UploadedFileName); File.Delete(testInfo.DownloadedFileName); } sftp.Disconnect(); Assert.IsTrue(hashMatches, "Hash does not match"); Assert.IsTrue(uploadDownloadSizeOk, "Uploaded and downloaded bytes does not match"); } }
public void go(string filename) { if (string.IsNullOrWhiteSpace(filename) || connInfo == null || config.sftpEnabled == false) { Log.Debug("Not doing SFTP because it wasn't configured properly or at all"); return; } FileInfo fi = new FileInfo(filename); if (!fi.Exists) { Log.Error("Can't open file for SFTPing: " + filename); return; } if (!fi.DirectoryName.StartsWith(config.localBaseFolder)) { Log.Error("Can't figure out where the file " + filename + " is relative to the base dir"); return; } string rel = fi.DirectoryName.Replace(config.localBaseFolder, ""); if (rel.StartsWith(Path.DirectorySeparatorChar.ToString())) { rel = rel.Substring(1); } SftpClient client = new SftpClient(connInfo); string accum = ""; try { client.Connect(); string thedir = null; foreach (string str in rel.Split(Path.DirectorySeparatorChar)) { accum = accum + "/" + str; thedir = config.sftpRemoteFolder + "/" + accum; thedir = thedir.Replace("//", "/"); Log.Debug("Trying to create directory " + thedir); try { client.CreateDirectory(thedir); } catch (SshException) { } } FileStream fis = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); client.BeginUploadFile(fis, thedir + "/" + fi.Name, true, (fini) => { FileStream ffini = fini.AsyncState as FileStream; if (ffini != null) { ffini.Close(); } if (client != null && client.IsConnected) { client.Disconnect(); } Log.Debug("Upload finished!"); if (Program.frm != null) { Program.frm.SetStatus("Upload finished! / Ready"); } }, fis, (pct) => { if (Program.frm != null) { Program.frm.SetStatus("Uploaded " + pct.ToString() + " bytes"); } }); } catch (Exception aiee) { Log.Error("Error: " + aiee.Message); Log.Debug(aiee.StackTrace); } }
public void transferFiles(string[] filesToUpload) { //richTextBox1.AppendText("Creating client and connecting"); LogThis("\rCreating client and connecting..."); bool directoryAlreadyExists = false; int fileCount = filesToUpload.Count(); int fileCounter = 0; using (var client = new SftpClient(HostName, _port, UserName, Password)) { try { // connect to SFTP host: client.Connect(); OutputThis(string.Format("\rConnected to {0}", HostName)); // cd to the remote folder we want as the root: client.ChangeDirectory(WorkingDirectory); LogThis(string.Format("\rChanged directory to {0}", WorkingDirectory)); LogThis(string.Format("\rChanged directory to {0}", WorkingDirectory)); try { client.ChangeDirectory(WorkingDirectory + "/" + PhotoFTPFolderName); directoryAlreadyExists = true; } catch (Exception exDirError) { if (exDirError != null) { if (exDirError.Message.Contains("not found")) { directoryAlreadyExists = false; } } } if (directoryAlreadyExists == false) { client.CreateDirectory(PhotoFTPFolderName); LogThis("directory created."); } client.ChangeDirectory(WorkingDirectory + "/" + PhotoFTPFolderName); LogThis("set working directory to photo Directory"); LogThis(string.Format("\rset working directory to {0}", WorkingDirectory + "/" + PhotoFTPFolderName)); // manage the uploading of multiple files foreach (var file in filesToUpload) { fileCounter++; using (var fileStream = new FileStream(file, FileMode.Open)) { LogThis(string.Format("\rUploading {0} ({1:N0} bytes)", file, fileStream.Length)); client.BufferSize = 4 * 1024; // bypass Payload error large files //client.UploadFile(fileStream, Path.GetFileName(uploadfile)); // try async: var asyncResult = client.BeginUploadFile(fileStream, Path.GetFileName(file), null, null) as Renci.SshNet.Sftp.SftpUploadAsyncResult; //var asyncResult = async1 as CommandAsyncResult; while (!asyncResult.IsCompleted) { FileUploadingEventArgs args = new FileUploadingEventArgs(); args.BytesSentSoFar = asyncResult.UploadedBytes; args.FileNameInProgress = file; args.FileBytesTotal = fileStream.Length; args.FileNumberOfTotal = fileCounter; args.TotalNumberFilesToTransfer = fileCount; LogThis(string.Format("\rUploaded {0:#########}", (asyncResult.UploadedBytes * 1024))); OnFileUploading(args); Thread.Sleep(200); } LogThis(string.Format("\rUploaded {0:#########}", (asyncResult.UploadedBytes * 1024))); if (asyncResult.IsCompleted) { FileUploadCompletedEventArgs fileCompleteArgs = new FileUploadCompletedEventArgs(); fileCompleteArgs.UploadedFileName = file; fileCompleteArgs.BytesSent = asyncResult.UploadedBytes; client.EndUploadFile(asyncResult); OnFileUploadCompleted(fileCompleteArgs); // raise an event to tell the client we're done! //MessageBox.Show("File upload completed!", "File Upload", MessageBoxButtons.OK, MessageBoxIcon.Information); } //MessageBox.Show("File upload completed!", "File Upload", MessageBoxButtons.OK, MessageBoxIcon.Information); } } } catch (Exception ex) { if (ex == null) { throw; } else { LogThis(ex.Message); // throw this exception so the consumer knows throw ex; } } finally { client.Disconnect(); } } }
// TODO: cancellationToken public static Task UploadFileAsync(this SftpClient sftpClient, Stream input, string path, bool canOverride = true) => Task.Factory.FromAsync(sftpClient.BeginUploadFile(input, path, canOverride, null, null), sftpClient.EndUploadFile);
public void transferFile() { //richTextBox1.AppendText("Creating client and connecting"); LogThis("\rCreating client and connecting..."); bool directoryAlreadyExists = false; using (var client = new SftpClient(HostName, _port, UserName, Password)) { try { // connect to SFTP host: client.Connect(); OutputThis(string.Format("\rConnected to {0}", HostName)); // cd to the remote folder we want as the root: client.ChangeDirectory(WorkingDirectory); LogThis(string.Format("\rChanged directory to {0}", WorkingDirectory)); LogThis(string.Format("\rChanged directory to {0}", WorkingDirectory)); // this just lists the current [root] folder contents to make sure we're where we think we are: for testing only //var listDirectory = client.ListDirectory(workingdirectory); //LogThis("\rListing directory:"); //// event args for listing directory event: //ListingDirectoryEventArgs listArgs = new ListingDirectoryEventArgs(); //foreach (var fi in listDirectory) //{ // listArgs.FolderName = workingdirectory; // listArgs.FileName = fi.Name; // OnListingDirectory(listArgs); // LogThis(string.Format("\r{0}", fi.Name)); //} // make the new directory on the server, test if it already exists though: // a bug in client.Exists prevents me from using it reliably, so just try to // cd to the dir and trap for the error if it doesn't exist: //if (client.Exists(workingdirectory + "/" + PhotoFTPFolderName) == false) //{ // client.CreateDirectory(PhotoFTPFolderName); // LogThis("directory created."); //} try { client.ChangeDirectory(WorkingDirectory + "/" + PhotoFTPFolderName); directoryAlreadyExists = true; } catch (Exception exDirError) { if (exDirError != null) { if (exDirError.Message.Contains("not found")) { directoryAlreadyExists = false; } } } if (directoryAlreadyExists == false) { client.CreateDirectory(PhotoFTPFolderName); LogThis("directory created."); } client.ChangeDirectory(WorkingDirectory + "/" + PhotoFTPFolderName); LogThis("set working directory to photo Directory"); LogThis(string.Format("\rset working directory to {0}", WorkingDirectory + "/" + PhotoFTPFolderName)); //listDirectory = client.ListDirectory(workingdirectory); //LogThis("\rListing directory:"); //foreach (var fi in listDirectory) //{ // LogThis(string.Format("\r{0}", fi.Name)); //} using (var fileStream = new FileStream(UploadFileName, FileMode.Open)) { LogThis(string.Format("\rUploading {0} ({1:N0} bytes)", UploadFileName, fileStream.Length)); client.BufferSize = 4 * 1024; // bypass Payload error large files //client.UploadFile(fileStream, Path.GetFileName(uploadfile)); // try async: var asyncResult = client.BeginUploadFile(fileStream, Path.GetFileName(UploadFileName), null, null) as Renci.SshNet.Sftp.SftpUploadAsyncResult; //var asyncResult = async1 as CommandAsyncResult; while (!asyncResult.IsCompleted) { FileUploadingEventArgs args = new FileUploadingEventArgs(); args.BytesSentSoFar = asyncResult.UploadedBytes; args.FileNameInProgress = UploadFileName; args.FileBytesTotal = fileStream.Length; LogThis(string.Format("\rUploaded {0:#########}", (asyncResult.UploadedBytes * 1024))); OnFileUploading(args); Thread.Sleep(200); } LogThis(string.Format("\rUploaded {0:#########}", (asyncResult.UploadedBytes * 1024))); if (asyncResult.IsCompleted) { FileUploadCompletedEventArgs fileCompleteArgs = new FileUploadCompletedEventArgs(); fileCompleteArgs.UploadedFileName = UploadFileName; fileCompleteArgs.BytesSent = asyncResult.UploadedBytes; client.EndUploadFile(asyncResult); OnFileUploadCompleted(fileCompleteArgs); // raise an event to tell the client we're done! //MessageBox.Show("File upload completed!", "File Upload", MessageBoxButtons.OK, MessageBoxIcon.Information); } //MessageBox.Show("File upload completed!", "File Upload", MessageBoxButtons.OK, MessageBoxIcon.Information); } } catch (Exception ex) { if (ex == null) { throw; } else { LogThis(ex.Message); // throw this exception so the consumer knows throw ex; } } finally { client.Disconnect(); } } }
public void Test_Sftp_Multiple_Async_Upload_And_Download_10Files_5MB_Each() { var maxFiles = 10; var maxSize = 5; RemoveAllFiles(); using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { sftp.Connect(); var testInfoList = new Dictionary <string, TestInfo>(); for (int i = 0; i < maxFiles; i++) { var testInfo = new TestInfo(); testInfo.UploadedFileName = Path.GetTempFileName(); testInfo.DownloadedFileName = Path.GetTempFileName(); testInfo.RemoteFileName = Path.GetRandomFileName(); this.CreateTestFile(testInfo.UploadedFileName, maxSize); // Calculate hash value testInfo.UploadedHash = CalculateMD5(testInfo.UploadedFileName); testInfoList.Add(testInfo.RemoteFileName, testInfo); } var uploadWaitHandles = new List <WaitHandle>(); // Start file uploads foreach (var remoteFile in testInfoList.Keys) { var testInfo = testInfoList[remoteFile]; testInfo.UploadedFile = File.OpenRead(testInfo.UploadedFileName); testInfo.UploadResult = sftp.BeginUploadFile(testInfo.UploadedFile, remoteFile, null, null) as SftpUploadAsyncResult; uploadWaitHandles.Add(testInfo.UploadResult.AsyncWaitHandle); } // Wait for upload to finish bool uploadCompleted = false; while (!uploadCompleted) { // Assume upload completed uploadCompleted = true; foreach (var testInfo in testInfoList.Values) { var sftpResult = testInfo.UploadResult; if (!testInfo.UploadResult.IsCompleted) { uploadCompleted = false; } } Thread.Sleep(500); } // End file uploads foreach (var remoteFile in testInfoList.Keys) { var testInfo = testInfoList[remoteFile]; sftp.EndUploadFile(testInfo.UploadResult); testInfo.UploadedFile.Dispose(); } // Start file downloads var downloadWaitHandles = new List <WaitHandle>(); foreach (var remoteFile in testInfoList.Keys) { var testInfo = testInfoList[remoteFile]; testInfo.DownloadedFile = File.OpenWrite(testInfo.DownloadedFileName); testInfo.DownloadResult = sftp.BeginDownloadFile(remoteFile, testInfo.DownloadedFile, null, null) as SftpDownloadAsyncResult; downloadWaitHandles.Add(testInfo.DownloadResult.AsyncWaitHandle); } // Wait for download to finish bool downloadCompleted = false; while (!downloadCompleted) { // Assume download completed downloadCompleted = true; foreach (var testInfo in testInfoList.Values) { var sftpResult = testInfo.DownloadResult; if (!testInfo.DownloadResult.IsCompleted) { downloadCompleted = false; } } Thread.Sleep(500); } var hashMatches = true; var uploadDownloadSizeOk = true; // End file downloads foreach (var remoteFile in testInfoList.Keys) { var testInfo = testInfoList[remoteFile]; sftp.EndDownloadFile(testInfo.DownloadResult); testInfo.DownloadedFile.Dispose(); testInfo.DownloadedHash = CalculateMD5(testInfo.DownloadedFileName); if (!(testInfo.UploadResult.UploadedBytes > 0 && testInfo.DownloadResult.DownloadedBytes > 0 && testInfo.DownloadResult.DownloadedBytes == testInfo.UploadResult.UploadedBytes)) { uploadDownloadSizeOk = false; } if (!testInfo.DownloadedHash.Equals(testInfo.UploadedHash)) { hashMatches = false; } } // Clean up after test foreach (var remoteFile in testInfoList.Keys) { var testInfo = testInfoList[remoteFile]; sftp.DeleteFile(remoteFile); File.Delete(testInfo.UploadedFileName); File.Delete(testInfo.DownloadedFileName); } sftp.Disconnect(); Assert.IsTrue(hashMatches, "Hash does not match"); Assert.IsTrue(uploadDownloadSizeOk, "Uploaded and downloaded bytes does not match"); } }
public void BeginUploadFileTest1() { ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value Stream input = null; // TODO: Initialize to an appropriate value string path = string.Empty; // TODO: Initialize to an appropriate value bool canOverride = false; // TODO: Initialize to an appropriate value AsyncCallback asyncCallback = null; // TODO: Initialize to an appropriate value object state = null; // TODO: Initialize to an appropriate value Action<ulong> uploadCallback = null; // TODO: Initialize to an appropriate value IAsyncResult expected = null; // TODO: Initialize to an appropriate value IAsyncResult actual; actual = target.BeginUploadFile(input, path, canOverride, asyncCallback, state, uploadCallback); Assert.AreEqual(expected, actual); Assert.Inconclusive("Verify the correctness of this test method."); }
public void Test_Sftp_Ensure_Async_Delegates_Called_For_BeginFileUpload_BeginFileDownload_BeginListDirectory() { RemoveAllFiles(); using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { sftp.Connect(); string remoteFileName = Path.GetRandomFileName(); string localFileName = Path.GetRandomFileName(); bool uploadDelegateCalled = false; bool downloadDelegateCalled = false; bool listDirectoryDelegateCalled = false; IAsyncResult asyncResult; // Test for BeginUploadFile. CreateTestFile(localFileName, 1); using (var fileStream = File.OpenRead(localFileName)) { asyncResult = sftp.BeginUploadFile(fileStream, remoteFileName, delegate(IAsyncResult ar) { sftp.EndUploadFile(ar); uploadDelegateCalled = true; }, null); while (!asyncResult.IsCompleted) { Thread.Sleep(500); } } File.Delete(localFileName); Assert.IsTrue(uploadDelegateCalled, "BeginUploadFile"); // Test for BeginDownloadFile. asyncResult = null; using (var fileStream = File.OpenWrite(localFileName)) { asyncResult = sftp.BeginDownloadFile(remoteFileName, fileStream, delegate(IAsyncResult ar) { sftp.EndDownloadFile(ar); downloadDelegateCalled = true; }, null); while (!asyncResult.IsCompleted) { Thread.Sleep(500); } } File.Delete(localFileName); Assert.IsTrue(downloadDelegateCalled, "BeginDownloadFile"); // Test for BeginListDirectory. asyncResult = null; asyncResult = sftp.BeginListDirectory(sftp.WorkingDirectory, delegate(IAsyncResult ar) { sftp.EndListDirectory(ar); listDirectoryDelegateCalled = true; }, null); while (!asyncResult.IsCompleted) { Thread.Sleep(500); } Assert.IsTrue(listDirectoryDelegateCalled, "BeginListDirectory"); } }
// TODO: cancellationToken public static Task UploadFileAsync(this SftpClient sftpClient, Stream input, string path, bool canOverride = true, CancellationToken cancellationToken = default) { return(Task.Factory.FromAsync(sftpClient.BeginUploadFile(input, path, canOverride, null, null), sftpClient.EndUploadFile)); }
/// <summary> /// Метод копирования файла на хост /// </summary> /// <param name="fileName">имя файла</param> /// <param name="pathToFile">путь к файлу</param> /// <param name="pathDestination">путь, куда будет скопирован файл</param> /// <param name="ipAddress">ip адрес хоста</param> /// <param name="login">логин, для подключения к хосту</param> /// <param name="password">пароль, для подключения к хосту</param> public void SftpCopy(string fileName, string pathToFile, string pathDestination, string ipAddress, string login, string password, bool addToListBoxTask = true) { try { bool endRunThread = false; var startThread = new Thread(new ThreadStart(() => { //BackgroundWorker progressBarCopyWorker = new BackgroundWorker(); PasswordConnectionInfo connectionInfo = new PasswordConnectionInfo(ipAddress, 22, login, password); connectionInfo.Timeout = TimeSpan.FromSeconds(15); string fileFullName = System.IO.Path.Combine(pathToFile, fileName); string fileDestinationFullName = System.IO.Path.Combine(pathDestination, fileName); ItemListBoxTask curItemLBT = new ItemListBoxTask() { IPOrName = ipAddress, Description = $"Выполняется копирование: {fileName} в {pathDestination}", CVZNumber = $"ЦВЗ№{SelectedTT.NumberCVZ.ToString()}" }; #region Скопировать файл на хост // Проверка доступности файла if (File.Exists(fileFullName)) { //Dispatcher.Invoke(() => //{ if (addToListBoxTask) { Dispatcher.Invoke(() => { Bindings.listBoxTaskItemsSource.Add(curItemLBT); }); //ListBoxTask.Items.Add(curItemLBT); } using (FileStream stream = new FileStream(fileFullName, FileMode.Open, FileAccess.Read)) { curItemLBT.MaxValueProgressBar = stream.Length; //progressBarStatus.Maximum = stream.Length; } //progressBarStatus.Value = 0; //progressBarStatus.Visibility = Visibility.Visible; //Bindings.StatusBarText = $"Выполняется копирование файла {fileName}"; bool uploadFileStoped = false; UpdateProgressBarDelegate updProgress = new UpdateProgressBarDelegate(progressBarStatus.SetValue); //UpdateProgressBarDelegate updProgressItemTask = new UpdateProgressBarDelegate(progressBarStatus.SetValue); using (var sftp = new SftpClient(connectionInfo)) { try { sftp.Connect(); using (FileStream stream = new FileStream(fileFullName, FileMode.Open, FileAccess.Read)) { var startUpload = sftp.BeginUploadFile(stream, fileDestinationFullName, (asyncCallback) => { //sftp.EndUploadFile(startUpload); endRunThread = true; }, null, (progressBarStatusCallBack) => { var temp = curItemLBT.StopProcess; if (curItemLBT.StopProcess) { if (!uploadFileStoped) { try { uploadFileStoped = true; sftp.Disconnect(); endRunThread = true; } catch (Exception) { } } } Dispatcher.Invoke((Action)(() => { curItemLBT.CurValueProgressBar = (double)progressBarStatusCallBack; })); Dispatcher.Invoke(updProgress, System.Windows.Threading.DispatcherPriority.Render, new object[] { MetroProgressBar.ValueProperty, (double)progressBarStatusCallBack }); }); while (!startUpload.IsCompleted) { if (startUpload.IsCompleted) { stream.Close(); stream.Dispose(); endRunThread = true; } } Log(!uploadFileStoped ? $"Выполнено копирование {fileDestinationFullName} на хост {ipAddress}" : $"Прервано копирование {fileDestinationFullName} на хост {ipAddress}", false, true); } } //catch(excep) catch (Exception ex) { Log(!uploadFileStoped ? ex.Message : $"Прервано копирование {fileDestinationFullName} на хост {ipAddress}", false, true); //Log(ex.Message, true, false, ex.StackTrace); } finally { try { sftp.Disconnect(); sftp.Dispose(); } catch (Exception) { } } } } else { Log($"{fileFullName} не доступен", true, true); } #endregion //} })); startThread.Start(); //startThread.Suspend(); //new Thread(new ThreadStart(() => //{ // while (!endRunThread) // { // if (endRunThread) // { // int endD = 1; // } // } //})).Start(); } catch (Exception ex) { Log(ex.Message, true, true, ex.StackTrace); } }
public static async Task UploadFileAsync(SftpClient sftp, Stream file, string destination) { Func <Stream, string, AsyncCallback, object, IAsyncResult> begin = (stream, path, callback, state) => sftp.BeginUploadFile(stream, path, true, callback, state, null); await SSHRetryReset(sftp, async() => { await Task.Factory.FromAsync(begin, sftp.EndUploadFile, file, destination, null); return(true); }); }
public void Test_Sftp_Ensure_Async_Delegates_Called_For_BeginFileUpload_BeginFileDownload_BeginListDirectory() { using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { sftp.Connect(); string remoteFileName = Path.GetRandomFileName(); string localFileName = Path.GetRandomFileName(); bool uploadDelegateCalled = false; bool downloadDelegateCalled = false; bool listDirectoryDelegateCalled = false; IAsyncResult asyncResult; // Test for BeginUploadFile. CreateTestFile(localFileName, 1); using (var fileStream = File.OpenRead(localFileName)) { asyncResult = sftp.BeginUploadFile(fileStream, remoteFileName, delegate(IAsyncResult ar) { sftp.EndUploadFile(ar); uploadDelegateCalled = true; }, null); while (!asyncResult.IsCompleted) { Thread.Sleep(500); } } File.Delete(localFileName); Assert.IsTrue(uploadDelegateCalled, "BeginUploadFile"); // Test for BeginDownloadFile. asyncResult = null; using (var fileStream = File.OpenWrite(localFileName)) { asyncResult = sftp.BeginDownloadFile(remoteFileName, fileStream, delegate(IAsyncResult ar) { sftp.EndDownloadFile(ar); downloadDelegateCalled = true; }, null); while (!asyncResult.IsCompleted) { Thread.Sleep(500); } } File.Delete(localFileName); Assert.IsTrue(downloadDelegateCalled, "BeginDownloadFile"); // Test for BeginListDirectory. asyncResult = null; asyncResult = sftp.BeginListDirectory(sftp.WorkingDirectory, delegate(IAsyncResult ar) { sftp.EndListDirectory(ar); listDirectoryDelegateCalled = true; }, null); while (!asyncResult.IsCompleted) { Thread.Sleep(500); } Assert.IsTrue(listDirectoryDelegateCalled, "BeginListDirectory"); } }
private void UploadFilesFromFilemanager() { string destpathroot = txtRemoteFolderPath.Text; if (!destpathroot.EndsWith("/")) { destpathroot += "/"; } var filelist = new Dictionary<string, string>(); foreach (var item in lvLocalBrowser.SelectedItems.Cast<EXImageListViewItem>().Where(item => (string) item.Tag != "[..]")) { if ((string)item.Tag == "File") { filelist.Add(item.MyValue, destpathroot + Path.GetFileName(item.MyValue)); } if ((string)item.Tag == "Folder") { string folder = Path.GetDirectoryName(item.MyValue); folder = folder.EndsWith("\\") ? folder : folder + "\\"; string[] files = Directory.GetFiles(item.MyValue, "*.*", SearchOption.AllDirectories); // Display all the files. foreach (string file in files) { filelist.Add(Path.GetFullPath(file), destpathroot + Path.GetFullPath(file).Replace(folder,"").Replace("\\","/")); } } } long fulllength = filelist.Sum(file => new FileInfo(file.Key).Length); MessageBox.Show(Tools.Misc.LengthToHumanReadable(fulllength)); var ssh = new SftpClient(txtHost.Text, int.Parse(this.txtPort.Text), txtUser.Text, txtPassword.Text); ssh.Connect(); ThreadPool.QueueUserWorkItem(state => { long totaluploaded = 0; foreach (var file in filelist) { CreatSSHDir(ssh, file.Value); var s = new FileStream(file.Key, FileMode.Open); var i = ssh.BeginUploadFile(s, file.Value) as SftpUploadAsyncResult; while (!i.IsCompleted) { SetProgressStatus(totaluploaded + (long)i.UploadedBytes, fulllength); } ssh.EndUploadFile(i); totaluploaded += s.Length; } MessageBox.Show(Language.SSHTransfer_StartTransfer_Upload_completed_); EnableButtons(); ssh.Disconnect(); }); }