Renci SSH.NET:是否可以创建包含不存在的子文件夹的文件夹

时间:2016-04-12 06:15:19

标签: c# recursion ssh sftp ssh.net

我目前正在使用Renci SSH.NET使用SFTP将文件和文件夹上传到Unix服务器,并使用

创建目录
sftp.CreateDirectory("//server/test/test2");

完美无缺,只要文件夹" test"已经存在。如果它没有,则CreateDirectory方法失败,并且每次当您尝试创建包含多个级别的目录时都会发生这种情况。

是否有一种优雅的方式来递归生成字符串中的所有目录?我假设CreateDirectory方法自动执行此操作。

5 个答案:

答案 0 :(得分:9)

别无他法。

只需迭代目录级别,使用SftpClient.GetAttributes测试每个级别,并创建不存在的级别。

static public void CreateDirectoryRecursively(this SftpClient client, string path)
{
    string current = "";

    if (path[0] == '/')
    {
        path = path.Substring(1);
    }

    while (!string.IsNullOrEmpty(path))
    {
        int p = path.IndexOf('/');
        current += '/';
        if (p >= 0)
        {
            current += path.Substring(0, p);
            path = path.Substring(p + 1);
        }
        else
        {
            current += path;
            path = "";
        }

        try
        {
            SftpFileAttributes attrs = client.GetAttributes(current);
            if (!attrs.IsDirectory)
            {
                throw new Exception("not directory");
            }
        }
        catch (SftpPathNotFoundException)
        {
            client.CreateDirectory(current);
        }
    }
}

答案 1 :(得分:7)

Martin Prikryl提供的代码略有改进

不要将Exceptions用作流控制机制。这里更好的选择是先检查当前路径是否存在。

var selectedValues = $("#sourceValues").val().split(',');
var $multiSelect = $(".select2").select2();
$multiSelect.val(selectedValues).trigger("change");

而不是try catch构造

if (client.Exists(current))
{
    SftpFileAttributes attrs = client.GetAttributes(current);
    if (!attrs.IsDirectory)
    {
        throw new Exception("not directory");
    }
}
else
{
    client.CreateDirectory(current);
}

答案 2 :(得分:2)

嗨,我发现我的答案很明确。自从找到这篇旧文章以来,我认为其他人也可能会偶然发现它。公认的答案不是那么好,所以这是我的看法。它不使用任何计数的mm头,因此我认为它更容易理解。

public void CreateAllDirectories(SftpClient client, string path)
    {
        // Consistent forward slashes
        path = path.Replace(@"\", "/");
        foreach (string dir in path.Split('/'))
        {
            // Ignoring leading/ending/multiple slashes
            if (!string.IsNullOrWhiteSpace(dir))
            {
                if(!client.Exists(dir))
                {
                    client.CreateDirectory(dir);
                }
                client.ChangeDirectory(dir);
            }
        }
        // Going back to default directory
        client.ChangeDirectory("/");
    }

答案 3 :(得分:1)

FWIW,这是我相当简单的看法。一个要求是服务器目标路径由正斜率分隔,这是常态。我在调用函数之前检查了这个。

    private void CreateServerDirectoryIfItDoesntExist(string serverDestinationPath, SftpClient sftpClient)
    {
        if (serverDestinationPath[0] == '/')
            serverDestinationPath = serverDestinationPath.Substring(1);

        string[] directories = serverDestinationPath.Split('/');
        for (int i = 0; i < directories.Length; i++)
        {
            string dirName = string.Join("/", directories, 0, i + 1);
            if (!sftpClient.Exists(dirName))
                sftpClient.CreateDirectory(dirName);
        }
    }

HTH

答案 4 :(得分:0)

对使用范围的已接受答案进行了一些修改。

在这种情况下,这可能毫无意义,因为sftp客户端的开销远远大于复制字符串,但在其他类似情况下也可能有用:

        public static void EnsureDirectory(this SftpClient client, string path)
        {
            if (path.Length is 0)
                return;

            var curIndex = 0;
            var todo = path.AsSpan();
            if (todo[0] == '/' || todo[0] == '\\')
            {
                todo = todo.Slice(1);
                curIndex++;
            }

            while (todo.Length > 0)
            {
                var endOfNextIndex = todo.IndexOf('/');
                if (endOfNextIndex < 0)
                    endOfNextIndex = todo.IndexOf('\\');

                string current;
                if (endOfNextIndex >= 0)
                {
                    curIndex += endOfNextIndex + 1;
                    current = path.Substring(0, curIndex);
                    todo = path.AsSpan().Slice(curIndex);
                }
                else
                {
                    current = path;
                    todo = ReadOnlySpan<char>.Empty;
                }

                try
                {
                    client.CreateDirectory(current);
                }
                catch (SshException ex) when (ex.Message == "Already exists.") { }
            }
        }
相关问题