BeginUploadFile() public method

Begins an asynchronous uploading the stream into remote file.

Method calls made by this method to input, may under certain conditions result in exceptions thrown by the stream.

If the remote file already exists, it is overwritten and truncated.

is null. is null or contains only whitespace characters. Client is not connected. Permission to list the contents of the directory was denied by the remote host. -or- A SSH command was denied by the server. A SSH error where is the message from the remote host. The method was called after the client was disposed.
public BeginUploadFile ( Stream input, string path ) : IAsyncResult
input Stream Data input stream.
path string Remote file path.
return IAsyncResult
Esempio n. 1
0
        public bool UploadToSFTP(MemoryStream ms, string filename, bool overwrite)
        {
            string strPath = sshPath;
              if (!strPath.StartsWith("/")) {
            strPath = "/" + strPath;
              }
              if (!strPath.EndsWith("/")) {
            strPath += "/";
              }

              bool bRet = true;
              bool bWait = true;

              sshError = "";

              if (sshConnection == null || !sshConnection.IsConnected) {
            bool bResume = false;
            bool bOK = false;
            connectionDoneCallback = (bool bSuccess) => {
              bOK = bSuccess;
              bResume = true;
            };
            Connect();
            while (!bResume) System.Threading.Thread.Sleep(1);
            if (!bOK) {
              sshError = "Couldn't connect to server.";
              return false;
            }
              }

              try {
            this.ProgressBar.Start(filename, ms.Length);
            ms.Seek(0, SeekOrigin.Begin);
            IAsyncResult arUpload = null;
            AsyncCallback cbFinished = (IAsyncResult ar) => {
              bRet = true;
              bWait = false;
            };
            Action<ulong> cbProgress = new Action<ulong>((ulong offset) => {
              this.ProgressBar.Set((long)offset);
              if (this.ProgressBar.Canceled) {
            sshConnection.EndUploadFile(arUpload);
            bRet = false;
            bWait = false;
              }
            });
            try {
              arUpload = sshConnection.BeginUploadFile(ms, strPath + filename, overwrite, cbFinished, filename, cbProgress);
            } catch {
              // failed to upload, queue it for a retry after reconnecting
              sshConnection = null;
              connectionDoneCallback = (bool bSuccess) => {
            if (!bSuccess) {
              bRet = false;
              sshError = "Upload failed because couldn't connect to server.";
              bWait = false;
              return;
            }
            try {
              arUpload = sshConnection.BeginUploadFile(ms, strPath + filename, overwrite, cbFinished, filename, cbProgress);
            } catch (Exception ex) {
              bRet = false;
              sshError = "Upload failed twice: " + (ex.InnerException != null ? ex.InnerException.Message : ex.Message);
              bWait = false;
            }
              };
              Connect();
            }
              } catch (Exception ex) {
            bRet = false;
            bWait = false;
            sshError = ex.InnerException != null ? ex.InnerException.Message : ex.Message;
            throw ex;
              }

              while (bWait) System.Threading.Thread.Sleep(1);

              this.ProgressBar.Done();
              return bRet;
        }
                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();
                        });
                }
Esempio n. 3
0
        /// <inheritdoc />
        public Task UploadFileToServerAsync(Stream stream, string basePath, string fileName, bool overwrite = false)
        {
            if (String.IsNullOrWhiteSpace(fileName))
            {
                throw new ArgumentNullException(nameof(fileName));
            }
            if (String.IsNullOrWhiteSpace(basePath))
            {
                throw new ArgumentNullException(nameof(basePath));
            }

            if (stream == null)
            {
                throw new ArgumentNullException(fileName);
            }
            if (stream.Length == 0)
            {
                throw new ArgumentException(LNG.SftpClient_CanNotBeEmpty, nameof(stream));
            }

            return(_retryAsyncPolicy.ExecuteAsync(() =>
            {
                EnsureConnected();

                var filePath = GetFileFullPath(basePath, fileName);

                if (_sftpClient.Exists(filePath))
                {
                    // Check file size.
                    var attributes = _sftpClient.GetAttributes(filePath);
                    if (attributes.Size == stream.Length)
                    {
                        // Size is equal. Assume that files are equal. No need to upload.
                        _logger.LogWarning(String.Format(LNG.SftpClient_SameFileAlreadyExists, fileName));
                        return Task.CompletedTask;
                    }

                    if (overwrite)
                    {
                        // can overwrite, so delete file
                        _logger.LogWarning(String.Format(
                                               LNG.SftpClient_Overwriting,
                                               fileName,
                                               attributes.Size,
                                               stream.Length));
                        _sftpClient.DeleteFile(filePath);
                    }
                    else
                    {
                        // can't overwrite, it's error
                        throw new SshException(
                            String.Format(
                                LNG.SftpClient_DifferentFileAlreadyExists,
                                fileName,
                                attributes.Size,
                                stream.Length));
                    }
                }

                var sftpDirectory = Path.GetDirectoryName(filePath)
                                    ?.Replace(@"\", "/") // windows-linux compatibility
                                    ?? throw new InvalidOperationException("File path can't be mull");

                if (!_sftpClient.Exists(sftpDirectory))
                {
                    CreateDirectoryRecursively(sftpDirectory);
                }

                //TODO #3 check it, I think we don't need it here
                // we need to set position to start because temp stream can be used in another places
                stream.Position = 0;

                return Task.Factory.FromAsync(
                    _sftpClient.BeginUploadFile(
                        stream,
                        filePath,
                        false,
                        null,
                        null),
                    _sftpClient.EndUploadFile);
            }));
        }
                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();
                    }
                }
Esempio n. 5
-1
        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);
            }
        }