示例#1
0
文件: Sftp.cs 项目: royedwards/DRDNet
            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.
            }
示例#2
0
        /// <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);
            }
        }
示例#3
0
        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();
        }
示例#4
0
 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);
     }
 }
示例#5
0
 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);
     }
 }
示例#6
0
文件: Uploader.cs 项目: zzattack/NFU
        /// <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);
            }
        }
示例#7
0
        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);
        }
示例#8
0
        /// <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)));
        }
示例#9
0
        /// <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();
            }
        }
示例#10
0
        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();
                }
            }
        }
示例#11
0
        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");
            }
        }
示例#12
0
        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");
            }
        }
示例#13
0
        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");
            }
        }
示例#14
0
        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");
            }
        }
示例#15
0
 public void EndUploadFileTest()
 {
     ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
     SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
     IAsyncResult asyncResult = null; // TODO: Initialize to an appropriate value
     target.EndUploadFile(asyncResult);
     Assert.Inconclusive("A method that does not return a value cannot be verified.");
 }
 public void EndUploadFile(IAsyncResult ar)
 {
     ColoredConsole.WriteLine(ConsoleColor.Cyan, "SSH.NET: Ending upload of file...");
     _connection.EndUploadFile(ar);
     ColoredConsole.WriteLine(ConsoleColor.Green, "SSH.NET: Ended file uploaded.");
 }
示例#17
0
        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 void End_Upload()
 {
     SftpClt.EndUploadFile(async_upload_result);
     stream_upload.Close();
 }
示例#19
0
        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();
                }
            }
        }
                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();
                        });
                }