Erik Erik - 3 months ago 41
C# Question

Renci SSH.NET: Is it possible to create a folder containing a subfolder that does not exist

I am currently using Renci SSH.NET to upload files and folders to a Unix Server using SFTP, and creating directories using

sftp.CreateDirectory("//server/test/test2");


works perfectly, as long as the folder "test" already exists. If it doesn't, the
CreateDirectory
method fails, and this happens everytime when you try to create directories containing multiple levels.

Is there an elegant way to recursively generate all the directories in a string? I was assuming that the
CreateDirectory
method does that automatically.

Answer

There's no other way.

Just iterate directory levels, testing each level using SftpClient.GetAttributes and create the levels that does not exist.

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);
        }
    }
}
Comments