private void DeleteDirectory(SftpClient sftpClient, string path)
        {
            if (!sftpClient.Exists(path))
            {
                return;
            }

            foreach (var item in sftpClient.ListDirectory(path))
            {
                if (".".Equals(item.Name) || "..".Equals(item.Name))
                {
                    continue;
                }

                if (item.IsDirectory)
                {
                    DeleteDirectory(sftpClient, item.FullName);
                }
                else
                {
                    sftpClient.Delete(item.FullName);
                }
            }

            sftpClient.Delete(path);
        }
        void IFtpSession.Delete(string path)
        {
            if (string.IsNullOrWhiteSpace(path))
            {
                throw new ArgumentNullException(nameof(path));
            }

            _sftpClient.Delete(path);
        }
Example #3
0
            protected override async Task PerformIO()
            {
                bool hadToConnect = _client.ConnectIfNeeded();
                await Task.Run(() => { _client.Delete(Path); });

                _client.DisconnectIfNeeded(hadToConnect);
            }
 /// <summary>
 /// Deletes a directory.
 /// Idempotent, can be called multiple times (does not throw an exception if the directory does not exist).
 /// Note, this is different than the <see cref="System.IO.Directory.Delete(string)"/> behavior.
 /// </summary>
 public static void DeleteDirectoryOkIfNotExists(this SftpClient sftpClient, string directoryPath)
 {
     if (sftpClient.Exists(directoryPath))
     {
         sftpClient.Delete(directoryPath);
     }
 }
Example #5
0
        /// <summary>
        /// 上传
        /// </summary>
        /// <param name="stream">文件流</param>
        /// <param name="destinationFolder">服务器目录</param>
        /// <param name="fileName">保存的文件名</param>
        public void Upload(Stream stream, string destinationFolder, string fileName)
        {
            if (!destinationFolder.EndsWith("/"))
            {
                destinationFolder = destinationFolder + "/";
            }



            //创建文件夹
            CreateServerDirectoryIfItDoesntExist(destinationFolder);


            //按照项目来区分文件夹 例如
            //  /publisher/aaa
            //  /publisher/aaa/publish.zip
            //  /publisher/aaa/deploy
            //删除zip文件
            if (_sftpClient.Exists(destinationFolder + fileName))
            {
                _sftpClient.Delete(destinationFolder + fileName);
            }

            var publishUnzipFolder = destinationFolder + "publish";

            //删除发布文件夹
            if (_sftpClient.Exists(publishUnzipFolder))
            {
                DeleteDirectory(publishUnzipFolder);
            }

            CreateServerDirectoryIfItDoesntExist(publishUnzipFolder + "/");

            ChangeToFolder(destinationFolder);

            var fileSize = stream.Length;

            _lastProgressNumber = 0;

            _sftpClient.UploadFile(stream, fileName, (uploaded) =>
            {
                if (UploadEvent != null)
                {
                    UploadEvent(this, new UploadEventArgs
                    {
                        size         = fileSize,
                        uploadedSize = uploaded
                    });
                }
                else
                {
                    uploadProgress(fileSize, uploaded);
                }
            });

            if (_lastProgressNumber != 100)
            {
                _uploadLogger(100);
            }
        }
Example #6
0
        private void toolStripMenuItem3_Click(object sender, EventArgs e)
        {
            SftpFile file = lvFiles.FocusedItem.Tag as SftpFile;

            if (file == null)
            {
                return;
            }
            if (MessageBox.Show("确定要删除此文件?", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                var connectionInfo = new ConnectionInfo(txtIp.Text, int.Parse(txtPort.Text), txtUser.Text, new PasswordAuthenticationMethod(txtUser.Text, txtPassword.Text));

                using (var client = new SftpClient(connectionInfo))
                {
                    try
                    {
                        client.Connect();
                        if (file.IsRegularFile)
                        {
                            client.Delete(file.FullName);
                            MessageBox.Show("删除成功!");
                            refresh();
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("删除失败" + ex.Message);
                    }
                }
            }
        }
Example #7
0
        // Move file at the ftp
        public bool RemoteDelete(string target)
        {
            string _stage = "";

            try
            {
                //
                _stage = "Checkings";
                if (!pSFtp.Exists(target))
                {
                    throw new Exception("Target file does not found.");
                }

                //
                _stage = "Deleting remote file";
                pSFtp.Delete(target);
            }
            catch (Exception ex)
            {
                throw new Exception($"[RemoteDelete#{_stage}] {ex.Message}");
            }

            // OK
            return(true);
        }
Example #8
0
        /// <summary>
        /// Deletes the linux directory recursively.
        /// </summary>
        /// <param name="client">The client.</param>
        /// <param name="path">The path.</param>
        private static void DeleteLinuxDirectoryRecursive(SftpClient client, string path)
        {
            var files = client.ListDirectory(path);

            foreach (var file in files)
            {
                if (file.Name.Equals(LinuxCurrentDirectory) || file.Name.Equals(LinuxParentDirectory))
                {
                    continue;
                }

                if (file.IsDirectory)
                {
                    DeleteLinuxDirectoryRecursive(client, file.FullName);
                }

                try
                {
                    client.Delete(file.FullName);
                }
                catch
                {
                    ConsoleManager.ErrorWriteLine("WARNING: Failed to delete file or folder '" + file.FullName + "'");
                }
            }
        }
        public bool DeleteFilesAndFolders(List <string> remotePaths)
        {
            var errorOccured = false;

            //Create a client
            using (var sftp = new SftpClient(Host, Port, Username, Password))
            {
                //Connect
                sftp.Connect();
                //Iterate the collection
                foreach (var remoteFilepath in remotePaths)
                {
                    try
                    {
                        //...and delete each file
                        sftp.Delete(remoteFilepath);
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex.Message, ex);
                        if (ThrowErrors)
                        {
                            throw new Exception($"zAppDev.DotNet.Framework SFTPClient error in deleting file: {remoteFilepath}");
                        }
                    }
                }
                //Finally disconnect and dispose
                sftp.Disconnect();
            }

            return(!errorOccured);
        }
        /// <summary>
        /// Deletes the linux directory recursively.
        /// </summary>
        /// <param name="client">The client.</param>
        /// <param name="path">The path.</param>
        private static void DeleteLinuxDirectoryRecursive(SftpClient client, string path)
        {
            var files = client.ListDirectory(path);

            foreach (var file in files)
            {
                if (file.Name.Equals(LinuxCurrentDirectory) || file.Name.Equals(LinuxParentDirectory))
                {
                    continue;
                }

                if (file.IsDirectory)
                {
                    DeleteLinuxDirectoryRecursive(client, file.FullName);
                }

                try
                {
                    client.Delete(file.FullName);
                }
                catch
                {
                    $"WARNING: Failed to delete file or folder '{file.FullName}'".Error(nameof(DeleteLinuxDirectoryRecursive));
                }
            }
        }
Example #11
0
        private static void DeleteRecoursively(string path, SftpClient client)
        {
            var files = client.ListDirectory(path).Where(d => d.Name != "." && d.Name != "..");

            foreach (var fileSystemInfo in files)
            {
                if (fileSystemInfo.IsDirectory)
                {
                    client.Open(fileSystemInfo.FullName, FileMode.Open);
                    DeleteRecoursively(fileSystemInfo.FullName, client);
                }
                else
                {
                    client.Delete(fileSystemInfo.FullName);
                }
            }
            client.Delete(path);
        }
        /// <summary>
        /// Uploads the files.
        /// </summary>
        /// <param name="fileList">The file list.</param>
        /// <exception cref="System.Exception">Remote File Already Exists.</exception>
        public void UploadFiles(List <ISFTPFileInfo> fileList)
        {
            try
            {
                this.Log(String.Format("Connecting to Host: [{0}].", this.hostName), LogLevel.Minimal);

                using (SftpClient sftp = new SftpClient(this.hostName, this.portNumber, this.userName, this.passWord))
                {
                    sftp.Connect();

                    this.Log(String.Format("Connected to Host: [{0}].", this.hostName), LogLevel.Verbose);

                    // Upload each file
                    foreach (SFTPFileInfo sftpFile in fileList)
                    {
                        FileInfo fileInfo = new FileInfo(sftpFile.LocalPath);
                        if (sftpFile.RemotePath.EndsWith("/"))
                        {
                            sftpFile.RemotePath = Path.Combine(sftpFile.RemotePath, fileInfo.Name).Replace(@"\", "/");
                        }

                        // if file exists can we overwrite it.
                        if (sftp.Exists(sftpFile.RemotePath))
                        {
                            if (sftpFile.OverwriteDestination)
                            {
                                this.Log(String.Format("Removing File: [{0}].", sftpFile.RemotePath), LogLevel.Verbose);
                                sftp.Delete(sftpFile.RemotePath);
                                this.Log(String.Format("Removed File: [{0}].", sftpFile.RemotePath), LogLevel.Verbose);
                            }
                            else
                            {
                                if (this.stopOnFailure)
                                {
                                    throw new Exception("Remote File Already Exists.");
                                }
                            }
                        }

                        using (FileStream file = File.OpenRead(sftpFile.LocalPath))
                        {
                            this.Log(String.Format("Uploading File: [{0}] -> [{1}].", fileInfo.FullName, sftpFile.RemotePath), LogLevel.Minimal);
                            sftp.UploadFile(file, sftpFile.RemotePath);
                            this.Log(String.Format("Uploaded File: [{0}] -> [{1}].", fileInfo.FullName, sftpFile.RemotePath), LogLevel.Verbose);
                        }
                    }
                }
                this.Log(String.Format("Disconnected from Host: [{0}].", this.hostName), LogLevel.Minimal);
            }
            catch (Exception ex)
            {
                this.Log(String.Format("Disconnected from Host: [{0}].", this.hostName), LogLevel.Minimal);
                this.ThrowException("Unable to Upload: ", ex);
            }
        }
 internal void Delete(string remotePath)
 {
     if (_sftpClient is NoAuthenticationSftpClient noAuthenticationSftpClient)
     {
         noAuthenticationSftpClient.RunCommand(new DeleteFile(remotePath));
     }
     else
     {
         _sftpClient.Delete(remotePath);
     }
 }
        /// <summary>
        /// Downloads files at sftp folder location to temp folder path on server
        /// </summary>
        /// <param name="sftpFolderLocatn"></param>
        /// <param name="folderDownloadPath"></param>
        /// <param name="fileNmesToMtchStr"></param>
        /// <param name="deleteFileFrmSrver"></param>
        /// <returns>return false if failed to find any files at location otherwise true</returns>
        public bool DownloadFilesFromSftp(string sftpFolderLocatn, string folderDownloadPath, string fileNmesToMtchStr, bool deleteFileFrmSrver)
        {
            try
            {
                if (objSftpClient == null)
                {
                    return(false);
                }
                objSftpClient.Connect();
                if (objSftpClient.IsConnected)
                {
                    var csvFiles = objSftpClient.ListDirectory(sftpFolderLocatn).Where(x => x.Name.ToLower().IndexOf(fileNmesToMtchStr) != -1);
                    if (csvFiles == null)
                    {
                        return(false);
                    }

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

            return(true);
        }
Example #15
0
        public static void DeleteRemoteFile(string host, string file, string username, string password)
        {
            using (var sftp = new SftpClient(host, username, password))
            {
                sftp.Connect();

                sftp.Delete(file);

                sftp.Disconnect();

            }
        }
Example #16
0
 /// <summary>
 /// 删除SFTP文件
 /// </summary>
 /// <param name="remoteFile">远程路径</param>
 public void Delete(string remoteFile)
 {
     try
     {
         Connect();
         sftp.Delete(remoteFile);
     }
     catch (Exception ex)
     {
         throw new Exception(string.Format("SFTP文件删除失败,原因:{0}", ex.Message));
     }
 }
Example #17
0
 /// <summary>
 /// 删除SFTP文件
 /// </summary>
 /// <param name="remoteFile">远程路径</param>
 public void Delete(string remoteFile)
 {
     try
     {
         Connect();
         sftp.Delete(remoteFile);
         Disconnect();
     }
     catch (Exception ex)
     {
         Console.WriteLine(string.Format("SFTP文件删除失败,原因:{0}", ex.Message));
     }
 }
Example #18
0
 /// <summary>
 /// 删除sftp文件
 /// </summary>
 /// <param name="remoteFile">远程路径</param>
 public void Delete(string remoteFile)
 {
     try
     {
         Connect(null);
         sftpClient.Delete(remoteFile);
         Disconnrct();
     }
     catch (Exception ex)
     {
         throw new Exception(string.Format("sftp文件删除失败,原因:{0}", ex.Message));
     }
 }
Example #19
0
 /// <summary>
 /// SFTP删除文件
 /// </summary>
 /// <param name="remoteFile">远程文件完整路径(带文件名)</param>
 public void Delete(string remoteFile)
 {
     try
     {
         Connect();
         _sftp.Delete(remoteFile);
         Disconnect();
     }
     catch (Exception ex)
     {
         throw new Exception($"SFTP删除远程文件失败,错误信息:{ ex.Message }");
     }
 }
Example #20
0
 /// <summary>
 /// SFTP 刪除檔案
 /// </summary>
 /// <param name="deleteFile">要刪除的檔案</param>
 public void Delete(string deleteFile)
 {
     try
     {
         Connect();
         sftp.Delete(deleteFile);
         Disconnect();
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Example #21
0
        /// <summary>
        /// 上传
        /// </summary>
        /// <param name="stream">文件流</param>
        /// <param name="destinationFolder">服务器目录</param>
        /// <param name="fileName">保存的文件名</param>
        public void Upload(Stream stream, string destinationFolder, string fileName)
        {
            if (!destinationFolder.EndsWith("/"))
            {
                destinationFolder = destinationFolder + "/";
            }



            //创建文件夹
            CreateServerDirectoryIfItDoesntExist(destinationFolder);


            //按照项目来区分文件夹 例如
            //  /publisher/aaa
            //  /publisher/aaa/publish.zip
            //  /publisher/aaa/deploy
            //删除zip文件
            if (_sftpClient.Exists(destinationFolder + fileName))
            {
                _sftpClient.Delete(destinationFolder + fileName);
            }

            var publishUnzipFolder = destinationFolder + "publish";

            //删除发布文件夹
            if (_sftpClient.Exists(publishUnzipFolder))
            {
                DeleteDirectory(publishUnzipFolder);
            }

            CreateServerDirectoryIfItDoesntExist(publishUnzipFolder + "/");

            ChangeToFolder(destinationFolder);

            var fileSize = stream.Length;

            _sftpClient.UploadFile(stream, fileName, (uploaded) => { uploadProgress(fileSize, uploaded); });
        }
Example #22
0
 /// <summary>
 /// 删除SFTP文件
 /// </summary>
 /// <param name="remoteFile">远程路径</param>
 public void Delete(string remoteFile)
 {
     try
     {
         Connect();
         sftp.Delete(remoteFile);
         Disconnect();
     }
     catch (Exception ex)
     {
         LogHelper.GetInstance().WriteLog(string.Format("SFTP文件删除失败,原因:{0}\r\n{1}", ex.Message, ex.StackTrace), LogType.错误);
         //throw new Exception(string.Format("SFTP文件删除失败,原因:{0}", ex.Message));
     }
 }
Example #23
0
 /// <summary>
 /// 删除SFTP文件
 /// </summary>
 /// <param name="remoteFile">远程路径</param>
 public void Delete(string remoteFile)
 {
     try
     {
         Connect();
         sftp.Delete(remoteFile);
         Disconnect();
     }
     catch (Exception ex)
     {
         // TxtLog.WriteTxt(CommonMethod.GetProgramName(), string.Format("SFTP文件删除失败,原因:{0}", ex.Message));
         throw new Exception(string.Format("SFTP文件删除失败,原因:{0}", ex.Message));
     }
 }
Example #24
0
        /// <summary>
        /// Удалить файл
        /// </summary>
        /// <param name="path">Полный путь к файлу</param>
        public bool DeleteFile(string path)
        {
            try
            {
                switch (typeSunc)
                {
                    #region SFTP
                case TypeSunc.SFTP:
                {
                    // Удаляем файл
                    sftp.Delete(path);
                    break;
                }
                    #endregion

                    #region FTP/FTPS
                case TypeSunc.FTP:
                {
                    // Удаляем файл
                    ftp.DeleteFile(path);
                    break;
                }
                    #endregion

                case TypeSunc.WebDav:
                {
                    var res = webDav.Delete(path).Result;
                    if (!res.IsSuccessful)
                    {
                        report.Base("DeleteFile", path, res);
                    }
                    break;
                }

                case TypeSunc.OneDrive:
                {
                    oneDrive.Delete(path).Wait();
                    break;
                }
                }

                return(true);
            }
            catch (Exception ex)
            {
                report.Base("DeleteFile", path, ex.ToString());
                return(false);
            }
        }
Example #25
0
 /// <summary>
 /// Deletes a file
 /// </summary>
 /// <param name="filePath"></param>
 public void Delete(string filePath)
 {
     try
     {
         try
         {
             Connect();
             _sftp.Delete(filePath);
         }
         catch
         {
             ReConnect();
             _sftp.Delete(filePath);
         }
     }
     catch (Exception ex)
     {
         throw ExceptionHandling.HandleComponentException(System.Reflection.MethodBase.GetCurrentMethod(), new SftpException("Unable to delete file [" + filePath + "].", ex));
     }
     finally
     {
         RaiseOnDisconnect();
     }
 }
        public virtual void FtpPickUp(string destinationFilePath, string fileName)
        {
            SftpClient sftpClient;

            var printxml = _config["printxml"] == "true";
            var url      = _config["sftpUrl"];
            var username = _config["sftpUsername"];
            var password = _config["sftpPassword"];

            sftpClient = new SftpClient(url, username, password);

            try
            {
                sftpClient.Connect();
            }
            catch (SshConnectionException e)
            {
                throw new CnpOnlineException("Error occured while attempting to establish an SFTP connection", e);
            }

            try {
                if (printxml)
                {
                    Console.WriteLine("Picking up remote file outbound/" + fileName + ".asc");
                    Console.WriteLine("Putting it at " + destinationFilePath);
                }

                FileStream downloadStream = new FileStream(destinationFilePath, FileMode.Create, FileAccess.ReadWrite);
                sftpClient.DownloadFile("outbound/" + fileName + ".asc", downloadStream);
                downloadStream.Close();
                if (printxml)
                {
                    Console.WriteLine("Removing remote file output/" + fileName + ".asc");
                }

                sftpClient.Delete("outbound/" + fileName + ".asc");
            }
            catch (SshConnectionException e) {
                throw new CnpOnlineException("Error occured while attempting to retrieve and save the file from SFTP",
                                             e);
            }
            catch (SftpPathNotFoundException e) {
                throw new CnpOnlineException("Error occured while attempting to locate desired SFTP file path", e);
            }
            finally {
                sftpClient.Disconnect();
            }
        }
Example #27
0
 public void DeleteFile(string remoteFilePath)
 {
     using var client = new SftpClient(_host, _port == 0 ? 22 : _port, _username, _password);
     try
     {
         client.Connect();
         client.Delete(remoteFilePath);
     }
     catch (Exception exception)
     {
         Console.WriteLine(exception);
     }
     finally
     {
         client.Disconnect();
     }
 }
        public void Sync(CrestronMonoDebuggerPackage package, string localPath, List <FileDeltaItem> fileListingDelta)
        {
            using (var client = new SftpClient(_host, _port, _username, _password))
            {
                client.Connect();

                foreach (FileDeltaItem deltaItem in fileListingDelta)
                {
                    try
                    {
                        if (deltaItem.Delete)
                        {
                            package.OutputWindowWriteLine($"Deleting remote file {deltaItem.Name}");
                            client.Delete($"{package.Settings.RelativePath}/{deltaItem.Name}");
                        }
                        else if (deltaItem.New)
                        {
                            package.OutputWindowWriteLine($"Uploading new file {deltaItem.Name}");
                            using (var stream = new FileStream(Path.Combine(localPath, deltaItem.Name), FileMode.Open))
                            {
                                client.UploadFile(stream, $"{package.Settings.RelativePath}/{deltaItem.Name}", true);
                            }
                        }
                        else if (deltaItem.Changed)
                        {
                            package.OutputWindowWriteLine($"Uploading changed file {deltaItem.Name}");
                            using (var stream = new FileStream(Path.Combine(localPath, deltaItem.Name), FileMode.Open))
                            {
                                client.UploadFile(stream, $"{package.Settings.RelativePath}/{deltaItem.Name}", true);
                            }
                        }
                        else
                        {
                            package.OutputWindowWriteLine($"File is unchanged: {deltaItem.Name}");
                        }
                    }
                    catch (Exception e)
                    {
                        package.OutputWindowWriteLine($"The was a problem {(deltaItem.Delete ? "deleting" : "uploading")} the file {deltaItem.Name}.");
                        package.DebugWriteLine(e);
                    }
                }

                client.Disconnect();
            }
        }
        private void ButtonSaveFile_Click(object sender, EventArgs e)                     // сохранение файла на сервер
        {
            using (var sftp = new SftpClient(ServerIP, ServerPort, "root", PasswordRoot)) //переменная для подключения
            {
                try
                {
                    sftp.Connect();                                          // попытка подключения
                    if (sftp.IsConnected)                                    // если подключились
                    {
                        if (comboBoxPath.SelectedItem == null)               // проверяем поле ввода на нулевое значение
                        {
                            MessageBox.Show("Выберите существующий объект"); // если поле нулевое, то вывод сообщения
                        }
                        else
                        {
                            string FilePath = comboBoxPath.SelectedItem.ToString(); // преобразуем выбранный пункт в стринг

                            if (sftp.Exists(FilePath + ".old"))                     // если файл old существует
                            {
                                sftp.Delete(FilePath + ".old");                     //то удаляем его
                            }
                            if (!sftp.Exists(FilePath))                             // если файл на пути не существует,
                            {
                                sftp.Create(FilePath);                              //то создаем его
                            }
                            else                                                    // если файл существует
                            {
                                sftp.RenameFile(FilePath, FilePath + ".old");       // то переименовываем  файл в .old
                            }
                            sftp.WriteAllText(FilePath, TextBoxEditor.Text);        // запись нового файла
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);    // вывод описания ошибки подключения
                }
                finally
                {
                    sftp.Disconnect();              // отключаемся от сервера
                }
            }
        }
Example #30
0
        /// <summary>
        /// Delete the specified directory or file from ftp server
        /// </summary>
        /// <param name="settings">ftp server settings</param>
        /// <param name="directoryOrFileName">Name of the directory or file</param>
        /// <returns></returns>
        public Task <bool> DeleteAsync(FTPSettings settings, string directoryOrFileName)
        {
            var connectionInfo      = CreateConnectionInfo(settings);
            var directoryOrFilePath = GetServerPath(settings.ServerPath);

            if (!directoryOrFilePath.EndsWith("/"))
            {
                directoryOrFilePath += "/";
            }
            directoryOrFilePath += directoryOrFileName;

            using (var sftp = new SftpClient(connectionInfo))
            {
                sftp.Connect();
                sftp.Delete(directoryOrFilePath);
                sftp.Disconnect();
            }

            return(Task.FromResult(true));
        }
Example #31
0
 public void DeleteTest()
 {
     ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
     SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
     string path = string.Empty; // TODO: Initialize to an appropriate value
     target.Delete(path);
     Assert.Inconclusive("A method that does not return a value cannot be verified.");
 }