Example #1
0
        /// <summary>
        /// Elimina un archivo del servidor SFTP.
        /// </summary>
        /// <param name="filePath">Ruta de Archivo/Directorio dentro del servidor.</param>
        /// <returns>Logrado o no logrado.</returns>
        /// <remarks>No validado.</remarks>
        public bool Delete(string filePath)
        {
            bool result = false;

            using (SftpClient client = new SftpClient(Host, User, Pass))
            {
                client.Connect();

                if (client.IsConnected)
                {
                    SftpFile file = client.Get(filePath);
                    if (file.IsDirectory)
                    {
                        client.DeleteDirectory(file.FullName);
                    }
                    else
                    {
                        client.DeleteFile(file.FullName);
                    }
                    result = true;
                    client.Disconnect();
                }
            }

            return(result);
        }
        public void DeleteDirectory(string server, int port, string directory)
        {
            directory = AdjustPath(server, directory);

            SftpClient client = null;

            try
            {
                client = OpenSftpClient(server, port);
                try
                {
                    client.DeleteDirectory(directory);
                }
                finally
                {
                    RecycleClient(client);
                    client = null;
                }
            }
            catch
            {
                try
                {
                    client.Disconnect();
                }
                catch { }
                try
                {
                    client.Dispose();
                }
                catch { }

                throw;
            }
        }
        void DeleteDirectory(string directory, bool recurse, bool deleteFiles, SftpClient conn)
        {
            try
            {
                directory = AdjustPath(conn.ConnectionInfo.Host, directory);

                if (conn.Exists(directory))
                {
                    List <SftpFile> items = conn.ListDirectory(directory).ToList();

                    if (recurse)
                    {
                        foreach (SftpFile i in items.Where(i => i.IsDirectory))
                        {
                            DeleteDirectory(i.FullName, recurse, deleteFiles);
                        }
                    }

                    if (!deleteFiles && items.Count(i => !i.IsDirectory) > 0)
                    {
                        throw new Exception("Directory (" + directory + ") is not empty.");
                    }

                    conn.DeleteDirectory(directory);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #4
0
        /// <summary>
        /// Deletes the directory recursively.
        /// </summary>
        /// <param name="remoteDirectory">The remote directory.</param>
        public static void DeleteDirectoryRecursive(string remoteDirectory, SftpClient Client)
        {
            if (!Client.Exists(remoteDirectory))
            {
                return;
            }

            foreach (var file in Client.ListDirectory(remoteDirectory))
            {
                if (file.Name.Equals(".") || file.Name.Equals(".."))
                {
                    continue;
                }

                if (file.IsDirectory)
                {
                    DeleteDirectoryRecursive(file.FullName, Client);
                }
                else
                {
                    Client.DeleteFile(file.FullName);
                }
            }

            Client.DeleteDirectory(remoteDirectory);
        }
        private void DeleteDirectory(SftpClient Sftp, string Path)
        {
            try
            {
                if (Sftp.Exists(Path))
                {
                    foreach (SftpFile File in Sftp.ListDirectory(Path))
                    {
                        if ((File.Name != ".") && (File.Name != ".."))
                        {
                            if (File.IsDirectory)
                            {
                                DeleteDirectory(Sftp, File.FullName);
                            }
                            else
                            {
                                Sftp.DeleteFile(File.FullName);
                            }
                        }
                    }

                    Sftp.DeleteDirectory(Path);
                }
            }
            catch (Exception e)
            {
                Logger.Error(string.Format("Delete directory {0} threw an exception. Ex: {1}", Path, e.Message));
            }
        }
 public void Test_Sftp_DeleteDirectory_Without_Connecting()
 {
     using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
     {
         sftp.DeleteDirectory("test");
     }
 }
Example #7
0
 public void Test_Sftp_DeleteDirectory_Without_Connecting()
 {
     using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
     {
         sftp.DeleteDirectory("test");
     }
 }
Example #8
0
        public void runQueue()
        {
            SetAppStatusText("Establishing SSH connection...");
            connectSSH();
            prepareIPAs();
            SetAppStatusBar(0);
            int i = 1;

            foreach (IPAInfo ipa in queue)
            {
                SetAppStatusText("Cracking app: " + ipa.AppName + " (" + i + "/" + queue.Count + ")");
                crackIPA(ipa);
                SetAppStatusBar((i * 100) / queue.Count);
                i++;
            }
            try
            {
                sftp.DeleteDirectory(DeviceTempDir);
            }
            catch (Exception e)
            {
            }
            ssh.Disconnect();
            sftp.Disconnect();
            AppHelper.DeleteDirectory(AppHelper.GetWorkingDirectory());
            MessageBox.Show("Cracking complete!");
            CloseWindow();
        }
Example #9
0
        /// <summary>
        /// Delete a test folder on a server
        /// </summary>
        /// <param name="serverName">The server to connect to</param>
        /// <param name="userName">The user to log into</param>
        /// <param name="password">The password of the user</param>
        /// <param name="folderName">The name of the test folder to delete</param>
        public static void DeleteFiles(string serverName, string userName, string password, string folderName)
        {
            using (SftpClient client = new SftpClient("serverName", userName, password))
            {
                client.Connect();

                // cd TestDir
                if (!client.Exists("TestDir"))
                {
                    return;
                }
                client.ChangeDirectory("TestDir");

                // Delete folder
                if (!string.IsNullOrWhiteSpace(folderName) && client.Exists(folderName))
                {
                    // client.DeleteDirectory is not recursive, so have to go in and delete every file first
                    Parallel.ForEach(client.ListDirectory(folderName), k =>
                    {
                        try
                        {
                            client.DeleteFile(k.FullName);
                        }
                        // Catch delete failures coming from trying to delete './' or '../'
                        catch (SshException) { }
                    });

                    client.DeleteDirectory(folderName);
                }

                client.Disconnect();
            }
        }
 public void DeleteDirectory(String fileName)
 {
     HandleExceptions(() =>
     {
         _sftpClient.DeleteDirectory(fileName);
     }, fileName);
 }
Example #11
0
        /// <summary>
        /// Delete Folder for target path
        /// </summary>
        /// <param name="folderPath">folder path</param>
        /// <returns>success or not</returns>
        public bool DeleteDirectory(string folderPath)
        {
            bool ret = false;

            if (IsSftpClientActive())
            {
                IEnumerable <SftpFile> sftpFiles = sftpClient.ListDirectory(folderPath);
                foreach (var file in sftpFiles)
                {
                    if ((file.Name != UPPER_PATH_1) && (file.Name != UPPER_PATH_2))
                    {
                        if (file.IsDirectory)
                        {
                            DeleteDirectory(file.FullName);
                        }
                        else
                        {
                            sftpClient.DeleteFile(file.FullName);
                        }
                    }
                }
                sftpClient.DeleteDirectory(folderPath);
                ret = true;
            }
            return(ret);
        }
Example #12
0
        private void DeleteDirectory(string path, bool useCommand = true)
        {
            if (useCommand)
            {
                //目前有2种会用到删除文件夹
                // 1.文件上传发现要上传的目录已存在
                // 2.旧的发布版本文件夹
                SshCommand cmd = _sshClient.RunCommand($"set -e;cd ~;\\rm -rf \"{path}\";");
                if (cmd.ExitStatus != 0)
                {
                    this._logger($"Delete directory:{path} fail", LogLevel.Warn);
                }
                return;
            }

            foreach (SftpFile file in _sftpClient.ListDirectory(path))
            {
                if ((file.Name != ".") && (file.Name != ".."))
                {
                    if (file.IsDirectory)
                    {
                        DeleteDirectory(file.FullName);
                    }
                    else
                    {
                        _sftpClient.DeleteFile(file.FullName);
                    }
                }
            }

            _sftpClient.DeleteDirectory(path);
        }
Example #13
0
        public void RemoveDirectory(string directoryPath)
        {
            using SftpClient sftpClient = CreateSftpClient();

            sftpClient.Connect();

            sftpClient.DeleteDirectory(directoryPath);

            sftpClient.Disconnect();
        }
Example #14
0
        public void Test_Sftp_DeleteDirectory_Null()
        {
            using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                sftp.Connect();

                sftp.DeleteDirectory(null);

                sftp.Disconnect();
            }
        }
Example #15
0
        public void Test_Sftp_DeleteDirectory_Which_Doesnt_Exists()
        {
            using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                sftp.Connect();

                sftp.DeleteDirectory("abcdef");

                sftp.Disconnect();
            }
        }
 internal void DeleteDirectory(string remotePath)
 {
     if (_sftpClient is NoAuthenticationSftpClient noAuthenticationSftpClient)
     {
         noAuthenticationSftpClient.RunCommand(new DeleteDirectory(remotePath));
     }
     else
     {
         _sftpClient.DeleteDirectory(remotePath);
     }
 }
        public void Test_Sftp_DeleteDirectory_Which_Doesnt_Exists()
        {
            using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                sftp.Connect();

                sftp.DeleteDirectory("abcdef");

                sftp.Disconnect();
            }
        }
        public void Test_Sftp_DeleteDirectory_Null()
        {
            using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                sftp.Connect();

                sftp.DeleteDirectory(null);

                sftp.Disconnect();
            }
        }
Example #19
0
        public static void DeleteRemoteDirectory(string host, string directory, string username, string password)
        {
            using (var sftp = new SftpClient(host, username, password))
            {
                sftp.Connect();

                sftp.DeleteDirectory(directory);

                sftp.Disconnect();

            }
        }
Example #20
0
 public static void DeleteRemoteFolderIfEmpty(SftpClient client, string remotePath, string remoteFolderName)
 {
     try
     {
         client.DeleteDirectory(remotePath + "/" + remoteFolderName);
     }
     catch (Exception e)
     {
         log.Error(e.Message, e);
         throw;
     }
 }
        private void Cleanup(SftpClient sftp, string path)
        {
            var files = sftp.ListDirectory(path);

            foreach (var file in files)
            {
                if (!file.IsDirectory)
                {
                    sftp.DeleteFile(file.FullName);
                }
            }
            sftp.DeleteDirectory(path);
        }
Example #22
0
        public override async Task DeleteDirectoryAsync(string path, CancellationToken cancellationToken = default)
        {
            await GetDirectoryAsync(path, cancellationToken);

            try
            {
                await Task.Run(() => client.DeleteDirectory(PrependRootPath(path)), cancellationToken);
            }
            catch (Exception exception)
            {
                throw Exception(exception);
            }
        }
Example #23
0
 public Task DeleteDirectory(string directoryPath)
 {
     return(HandleCommonExceptions(async() => {
         _logger?.LogDebug($"DeleteDirectory('{directoryPath}')");
         var files = await GetFiles(directoryPath);
         var fileRmReqs = files.Select(file => DeleteFile(CombinePath(directoryPath, file)));
         await Task.WhenAll(fileRmReqs);
         var dirs = await GetDirectories(directoryPath);
         var rmDirReqs = dirs.Select(dir => DeleteDirectory(CombinePath(directoryPath, dir)));
         await Task.WhenAll(rmDirReqs);
         _client.DeleteDirectory(directoryPath);
         _logger?.LogDebug($"DeleteDirectory('{directoryPath}'): done");
     }));
 }
        internal static bool DirectoryDeleteCreate(SftpClient client, string remotePath)
        {
            try
            {
                client.DeleteDirectory(remotePath);
                client.CreateDirectory(remotePath);
            }
            catch
            {
                return(false);
            }

            return(true);
        }
        public void Test_Sftp_DeleteDirectory_Which_No_Permissions()
        {
            if (Resources.USERNAME == "root")
                Assert.Fail("Must not run this test as root!");

            using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                sftp.Connect();

                sftp.DeleteDirectory("/usr");

                sftp.Disconnect();
            }
        }
Example #26
0
        public void Test_Sftp_DeleteDirectory_Which_No_Permissions()
        {
            if (Resources.USERNAME == "root")
            {
                Assert.Fail("Must not run this test as root!");
            }

            using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                sftp.Connect();

                sftp.DeleteDirectory("/usr");

                sftp.Disconnect();
            }
        }
Example #27
0
        private void DeleteDirectory(string path)
        {
            foreach (SftpFile file in _sftpClient.ListDirectory(path))
            {
                if ((file.Name != ".") && (file.Name != ".."))
                {
                    if (file.IsDirectory)
                    {
                        DeleteDirectory(file.FullName);
                    }
                    else
                    {
                        _sftpClient.DeleteFile(file.FullName);
                    }
                }
            }

            _sftpClient.DeleteDirectory(path);
        }
Example #28
0
 //サーバー上にあるフォルダを削除(サブディレクトも含む)
 public bool Directory_Delete(string To_Dir, bool IsErrorLogMode = false)
 {
     if (!IsConnected)
     {
         return(false);
     }
     else if (!SFTP_Server.IsConnected)
     {
         SFTP_Server.Connect();
     }
     try
     {
         if (!SFTP_Server.Exists(To_Dir))
         {
             return(false);
         }
         foreach (SftpFile file in SFTP_Server.ListDirectory(To_Dir))
         {
             if ((file.Name != ".") && (file.Name != ".."))
             {
                 if (file.IsDirectory)
                 {
                     Directory_Delete(file.FullName);
                 }
                 else
                 {
                     SFTP_Server.DeleteFile(file.FullName);
                 }
             }
         }
         SFTP_Server.DeleteDirectory(To_Dir);
         return(true);
     }
     catch (Exception e)
     {
         if (IsErrorLogMode)
         {
             Sub_Code.Error_Log_Write(e.Message);
         }
         return(false);
     }
 }
        /// <summary>
        /// 刪除資料夾(不可以刪除檔案)
        /// </summary>
        /// <param name="ftpFolderPath">資料夾路徑,根目錄請代空字串</param>
        /// <param name="folderName">資料夾名稱</param>
        /// <returns></returns>
        public FTPExecuteResult RemoveFolder(string ftpFolderPath, string folderName)
        {
            try
            {
                if (IsFolderExists(ftpFolderPath, folderName))
                {
                    _sftp.DeleteDirectory(string.Format("/{0}/{1}", ftpFolderPath, folderName));

                    return(FTPExecuteResult.Ok("成功刪除資料夾"));
                }
                else
                {
                    return(FTPExecuteResult.Fail(string.Format("SFTP刪除資料夾失敗,原因:{0}", "SFTP上無此資料夾")));
                }
            }
            catch (Exception ex)
            {
                return(FTPExecuteResult.Fail(string.Format("FTP刪除資料夾失敗,原因:{0}", ex.ToString())));
            }
        }
Example #30
0
        private static void ListFiles()
        {
            string host     = @"centosnote";
            string username = "******";
            string password = @"sftpuser";

            string remoteDirectory = "/home/sftpuser/ftproot";

            using (SftpClient sftp = new SftpClient(host, username, password))
            {
                try
                {
                    sftp.Connect();

                    var files = sftp.ListDirectory(remoteDirectory);

                    foreach (var file in files)
                    {
                        if (file.IsDirectory)
                        {
                            Console.WriteLine("Directory -> " + file.Name);
                        }
                        else if (file.IsRegularFile)
                        {
                            Console.WriteLine("File -> " + file.Name);
                        }
                        else
                        {
                            Console.WriteLine("Other -> " + file.Name);
                        }
                    }

                    sftp.DeleteDirectory("/home/sftpuser/ftproot/spanish/P456456");
                    sftp.Disconnect();
                }
                catch (Exception e)
                {
                    Console.WriteLine("An exception has been caught " + e.ToString());
                }
            }
        }
Example #31
0
        public void removeDirectory(string directoryToRemove)
        {
            using (var client = new SftpClient(HostName, _port, _username, _password))
            {
                try
                {
                    client.Connect();
                    LogThis(string.Format("\rConnected to {0}", HostName));

                    client.DeleteDirectory(directoryToRemove);
                    LogThis("\rdirectory removed!");
                }
                catch (Exception ex)
                {
                    LogThis(ex.Message);
                    // throw for the caller's benefit:
                    throw ex;
                }
                finally
                {
                    client.Disconnect();
                }
            }
        }
Example #32
0
        public static int DeleteDirectoryRecursively(this SftpClient sftp, string path, bool verbose)
        {
            var filesDeleted = 0;

            void ClearFiles(List <SftpFile> entities)
            {
                var files       = entities.Where(e => e.IsRegularFile).ToList();
                var directories = entities.Where(e => e.IsDirectory && (e.Name != "." && e.Name != "..")).ToList();

                foreach (var file in files)
                {
                    sftp.DeleteFile(file.FullName);
                    filesDeleted++;

                    if (verbose)
                    {
                        Console.WriteLine($"Deleted file {file.FullName}");
                    }
                }

                foreach (var dir in directories)
                {
                    ClearFiles(sftp.ListDirectory(dir.FullName).ToList());
                    sftp.DeleteDirectory(dir.FullName);

                    if (verbose)
                    {
                        Console.WriteLine($"Deleted directory {dir.FullName}");
                    }
                }
            }

            ClearFiles(sftp.ListDirectory(path).ToList());

            return(filesDeleted);
        }
Example #33
0
        public NtStatus DeleteDirectory(string fileName, DokanFileInfo info)
        {
            fileName = ToUnixStylePath(fileName);

            if (!sftpClient.Exists(fileName))
            {
                return(DokanResult.FileNotFound);
            }

            try
            {
                sftpClient.DeleteDirectory(fileName);
            }
            catch (SftpPermissionDeniedException)
            {
                return(DokanResult.AccessDenied);
            }
            catch (SshException)
            {
                return(DokanResult.InvalidParameter);
            }

            return(DokanResult.Success);
        }
        public void Test_Sftp_Change_Directory()
        {
            using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                sftp.Connect();

                Assert.AreEqual(sftp.WorkingDirectory, "/home/tester");

                sftp.CreateDirectory("test1");

                sftp.ChangeDirectory("test1");

                Assert.AreEqual(sftp.WorkingDirectory, "/home/tester/test1");

                sftp.CreateDirectory("test1_1");
                sftp.CreateDirectory("test1_2");
                sftp.CreateDirectory("test1_3");

                var files = sftp.ListDirectory(".");

                Assert.IsTrue(files.First().FullName.StartsWith(string.Format("{0}", sftp.WorkingDirectory)));

                sftp.ChangeDirectory("test1_1");

                Assert.AreEqual(sftp.WorkingDirectory, "/home/tester/test1/test1_1");

                sftp.ChangeDirectory("../test1_2");

                Assert.AreEqual(sftp.WorkingDirectory, "/home/tester/test1/test1_2");

                sftp.ChangeDirectory("..");

                Assert.AreEqual(sftp.WorkingDirectory, "/home/tester/test1");

                sftp.ChangeDirectory("..");

                Assert.AreEqual(sftp.WorkingDirectory, "/home/tester");

                files = sftp.ListDirectory("test1/test1_1");

                Assert.IsTrue(files.First().FullName.StartsWith(string.Format("{0}/test1/test1_1", sftp.WorkingDirectory)));

                sftp.ChangeDirectory("test1/test1_1");

                Assert.AreEqual(sftp.WorkingDirectory, "/home/tester/test1/test1_1");

                sftp.ChangeDirectory("/home/tester/test1/test1_1");

                Assert.AreEqual(sftp.WorkingDirectory, "/home/tester/test1/test1_1");

                sftp.ChangeDirectory("/home/tester/test1/test1_1/../test1_2");

                Assert.AreEqual(sftp.WorkingDirectory, "/home/tester/test1/test1_2");

                sftp.ChangeDirectory("../../");

                sftp.DeleteDirectory("test1/test1_1");
                sftp.DeleteDirectory("test1/test1_2");
                sftp.DeleteDirectory("test1/test1_3");
                sftp.DeleteDirectory("test1");

                sftp.Disconnect();
            }

            RemoveAllFiles();
        }
Example #35
0
 public void DeleteDirectoryTest()
 {
     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.DeleteDirectory(path);
     Assert.Inconclusive("A method that does not return a value cannot be verified.");
 }
        public void Test_Sftp_Change_Directory()
        {
            using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                sftp.Connect();

                Assert.AreEqual(sftp.WorkingDirectory, "/home/tester");

                sftp.CreateDirectory("test1");

                sftp.ChangeDirectory("test1");

                Assert.AreEqual(sftp.WorkingDirectory, "/home/tester/test1");

                sftp.CreateDirectory("test1_1");
                sftp.CreateDirectory("test1_2");
                sftp.CreateDirectory("test1_3");

                var files = sftp.ListDirectory(".");

                Assert.IsTrue(files.First().FullName.StartsWith(string.Format("{0}", sftp.WorkingDirectory)));

                sftp.ChangeDirectory("test1_1");

                Assert.AreEqual(sftp.WorkingDirectory, "/home/tester/test1/test1_1");

                sftp.ChangeDirectory("../test1_2");

                Assert.AreEqual(sftp.WorkingDirectory, "/home/tester/test1/test1_2");

                sftp.ChangeDirectory("..");

                Assert.AreEqual(sftp.WorkingDirectory, "/home/tester/test1");

                sftp.ChangeDirectory("..");

                Assert.AreEqual(sftp.WorkingDirectory, "/home/tester");

                files = sftp.ListDirectory("test1/test1_1");

                Assert.IsTrue(files.First().FullName.StartsWith(string.Format("{0}/test1/test1_1", sftp.WorkingDirectory)));

                sftp.ChangeDirectory("test1/test1_1");

                Assert.AreEqual(sftp.WorkingDirectory, "/home/tester/test1/test1_1");

                sftp.ChangeDirectory("/home/tester/test1/test1_1");

                Assert.AreEqual(sftp.WorkingDirectory, "/home/tester/test1/test1_1");

                sftp.ChangeDirectory("/home/tester/test1/test1_1/../test1_2");

                Assert.AreEqual(sftp.WorkingDirectory, "/home/tester/test1/test1_2");

                sftp.ChangeDirectory("../../");

                sftp.DeleteDirectory("test1/test1_1");
                sftp.DeleteDirectory("test1/test1_2");
                sftp.DeleteDirectory("test1/test1_3");
                sftp.DeleteDirectory("test1");

                sftp.Disconnect();
            }
        }