简体   繁体   English

Renci SSH.NET:如何删除非空目录?

[英]Renci SSH.NET: How to delete nonempty directory?

I am using Renci SSH.NET to access files and folders on a unix server. 我使用Renci SSH.NET访问unix服务器上的文件和文件夹。 I would like to delete a whole directory tree by specifying the base directory, but when I call sftp.DeleteDirectory(destination) , that call will only succeed if I pass an empty directory. 我想通过指定基目录来删除整个目录树,但是当我调用sftp.DeleteDirectory(destination) ,只有在我传递一个空目录时,该调用才会成功。

However, I would also like to be able to delete directories containing files or additional folders. 但是,我还希望能够删除包含文件或其他文件夹的目录。 Most .NET classes will handle that automatically, how can it be done in SSH.NET? 大多数.NET类都会自动处理,如何在SSH.NET中完成?

The SSH.NET library does not support any recursive operations. SSH.NET库不支持任何递归操作。 So recursive delete is not available either. 因此递归删除也不可用。

You have to use the SftpClient.ListDirectory method to recursively list all files and subfolders and delete them one by one. 您必须使用SftpClient.ListDirectory方法递归列出所有文件和子文件夹并逐个删除它们。

private static void DeleteDirectory(SftpClient client, string path)
{
    foreach (SftpFile file in client.ListDirectory(path))
    {
        if ((file.Name != ".") && (file.Name != ".."))
        {
            if (file.IsDirectory)
            {
                DeleteDirectory(client, file.FullName);
            }
            else
            {
                client.DeleteFile(file.FullName);
            }
        }
    }

    client.DeleteDirectory(path);
}

Or use another SFTP library. 或者使用其他SFTP库。

For example with WinSCP .NET assembly , you can use the Session.RemoveFiles method that can delete a directory recursively. 例如,使用WinSCP .NET程序集 ,您可以使用可以递归删除目录的Session.RemoveFiles方法

// Setup session options
SessionOptions sessionOptions = new SessionOptions
{
    Protocol = Protocol.Sftp,
    HostName = "example.com",
    UserName = "user",
    Password = "mypassword",
    SshHostKeyFingerprint = "ssh-rsa 2048 xxxxxxxxxxx...="
};

using (Session session = new Session())
{
    // Connect
    session.Open(sessionOptions);

    // Delete the directory recursively
    session.RemoveFiles("/directory/to/delete").Check();
}

WinSCP GUI can generate a code template for you. WinSCP GUI可以为您生成代码模板

(I'm the author of WinSCP) (我是WinSCP的作者)

try executing the command in ssh instead of using sftp rm -rf or rm -r 尝试在ssh中执行命令,而不是使用sftp rm -rf或rm -r

Code may look something like this: Renci.SshClient ssh1 = new SshCLient("server","user","password"); ssh1.connect(); ssh1.RunCommand("cd LandingZone;rm -rf <directoryName>"); ssh1.Disconnect(); 代码可能如下所示: Renci.SshClient ssh1 = new SshCLient("server","user","password"); ssh1.connect(); ssh1.RunCommand("cd LandingZone;rm -rf <directoryName>"); ssh1.Disconnect(); Renci.SshClient ssh1 = new SshCLient("server","user","password"); ssh1.connect(); ssh1.RunCommand("cd LandingZone;rm -rf <directoryName>"); ssh1.Disconnect();

You can delete a directory tree or a file dynamically using SSH.NET library (regardless if it is an empty directory or not) by specifying the remote path with these two methods: 您可以使用SSH.NET库动态删除目录树或文件(无论它是否为空目录),方法是使用以下两种方法指定远程路径:

  public bool DeleteRemoteDirectoryRecursive(string RemoteDirectoryPath)
  {
        if (string.IsNullOrEmpty(RemoteDirectoryPath))
        {                
            return false;
        }

        var ConnectionInfo = new ConnectionInfo(this.sftpHost, this.sftpPort, this.sftpUser, new PasswordAuthenticationMethod(this.sftpUser, this.sftpPassword));
        using (var client = new SftpClient(ConnectionInfo))
        {                
            client.Connect();

            if (!client.Exists(RemoteDirectoryPath))
            {                   
                client.Disconnect();
                client.Dispose();
                return false;
            }

            foreach (var file in client.ListDirectory(RemoteDirectoryPath))
            {
                if (file.Name.Equals(".") || file.Name.Equals(".."))
                    continue;

                if (file.IsDirectory)
                {
                    client.Disconnect();
                    DeleteRemoteDirectoryRecursive(file.FullName);
                }
                else
                    client.DeleteFile(file.FullName);
            }

            client.DeleteDirectory(RemoteDirectoryPath);

        }

        return true;
    }

    public bool Remove(string RemotePath)
    {
        bool ReturnResult = false;

        try
        {
            if (string.IsNullOrEmpty(RemotePath))
            {
                return false;
            }

            var ConnectionInfo = new ConnectionInfo(this.sftpHost, this.sftpPort, this.sftpUser, new PasswordAuthenticationMethod(this.sftpUser, this.sftpPassword));
            using (var client = new SftpClient(ConnectionInfo))
            {
                client.Connect();

                if (!client.Exists(RemotePath))
                {
                    client.Disconnect();
                    client.Dispose();
                    return false;
                }

                try
                {
                    //  path is directory
                    client.ChangeDirectory(RemotePath);
                    try
                    {
                        DeleteRemoteDirectoryRecursive(RemotePath);
                        ReturnResult = true;
                    }
                    catch
                    {
                        ReturnResult = false;
                    }

                }
                // path is a file
                catch
                {
                    try
                    {
                        client.DeleteFile(RemotePath);
                        ReturnResult = true;
                    }
                    catch
                    {
                        ReturnResult = false;
                    }
                }
            }
        }
        catch (Exception ex)
        {                
            ReturnResult = false;
        }
        return ReturnResult;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Renci SSH.NET:如何创建符号链接? - Renci SSH.NET: How to create symlinks? Renci SSH.NET中有什么方法可以检查SFTP目录权限吗? - Is there any method for checking SFTP directory permission in Renci SSH.NET? Renci SSH.NET:上传文件时的字符编码 - Renci SSH.NET: character encoding when uploading files 无法使用 SFTP/SSH.NET 从远程目录中删除文件? - Unable to delete files from a remote directory with SFTP/SSH.NET? 在 Renci SSH.NET 中启动自定义 SSH 子系统(相当于 ch.ethz ssh2.Session.StartSubSystem()) - Start custom SSH subsystem in Renci SSH.NET (an equivalent of ch.ethz ssh2.Session.StartSubSystem()) 如何使用SSH.Net进行安装? - How to su with SSH.Net? Renci SSH.NET:SftpClient.UploadFile无法上传大小超过1GB的文件 - Renci SSH.NET: SftpClient.UploadFile fails to upload files greater than 1GB in size Renci ssh.net 无法连接,因为目标机器主动拒绝 - Renci ssh.net No connection could be made because the target machine actively refused it SSH.NET [ObjectDisposedException:无法访问已处置的 object。 Object 名称:'Renci.SshNet.SshClient'。] - SSH.NET [ObjectDisposedException: Cannot access a disposed object. Object name: 'Renci.SshNet.SshClient'.] Renci SSH.NET:是否可以创建一个包含不存在的子文件夹的文件夹 - Renci SSH.NET: Is it possible to create a folder containing a subfolder that does not exist
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM