コード例 #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
        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);
            }
        }
コード例 #3
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);
            }
        }
コード例 #4
0
        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();
        }
コード例 #5
0
        public void SftpUploadAsyncResultConstructorTest()
        {
            AsyncCallback         asyncCallback = null; // TODO: Initialize to an appropriate value
            object                state         = null; // TODO: Initialize to an appropriate value
            SftpUploadAsyncResult target        = new SftpUploadAsyncResult(asyncCallback, state);

            Assert.Inconclusive("TODO: Implement code to verify target");
        }
コード例 #6
0
 private void OnTransferProgressChanged(SftpUploadAsyncResult e)
 {
     if (ProgressChanged != null)
     {
         progress.ChangeProgress((int)e.UploadedBytes, true);
         ProgressChanged(progress);
     }
 }
コード例 #7
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);
            }
        }
コード例 #8
0
        private void ___UPLOAD_THREAD()
        {
            Modify_progressBar2(progressBar2, 0);
            Modify_UploadStatusTextBox(UploadStatusTextBox, "");
            Modify_UploadStatusTextBox(UploadStatusTextBox, "Initializing..." + System.Environment.NewLine);

            try
            {
                using (SftpClient client = new SftpClient(con))
                {
                    client.Connect();
                    Console.WriteLine("Connected to the server!");
                    Modify_UploadStatusTextBox(UploadStatusTextBox, "Connected to the server " + this.hostname + "." + System.Environment.NewLine);

                    foreach (string localFileName in SelectedFileTextbox.Lines)
                    {
                        UPLOAD(client, localFileName);
                    }

                    if (sftpAsyncrUpload.IsUploadCanceled)
                    {
                        Modify_progressBar2(progressBar2, 0);
                        Modify_UploadLabel(UploadLabel, "Status: Canceled");
                        Modify_UploadBtnStatus(UploadBtn);
                        sftpAsyncrUpload = null;
                    }
                    else
                    {
                        Modify_progressBar2(progressBar2, 0);
                        Modify_UploadLabel(UploadLabel, "Status: Completed");
                        Modify_UploadBtnStatus(UploadBtn);
                        sftpAsyncrUpload = null;
                    }

                    client.Disconnect();
                }
            }
            catch (Exception ex)
            {
                Modify_progressBar2(progressBar2, 0);
                Modify_UploadLabel(UploadLabel, "Status: Error occurred");
                Modify_UploadStatusTextBox(UploadStatusTextBox, "Error occurred, try again!" + System.Environment.NewLine);
                Modify_UploadBtnStatus(UploadBtn);
                sftpAsyncrUpload = null;
                MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }