SSH.NET Загрузить всю папку

Я использую SSH.NET в С# 2015.

С помощью этого метода я могу загрузить файл на свой SFTP-сервер.

public void upload()
{
    const int port = 22;
    const string host = "*****";
    const string username = "*****";
    const string password = "*****";
    const string workingdirectory = "*****";
    string uploadfolder = @"C:\test\file.txt";

    Console.WriteLine("Creating client and connecting");
    using (var client = new SftpClient(host, port, username, password))
    {
        client.Connect();
        Console.WriteLine("Connected to {0}", host);

        client.ChangeDirectory(workingdirectory);
        Console.WriteLine("Changed directory to {0}", workingdirectory);

        using (var fileStream = new FileStream(uploadfolder, FileMode.Open))
        {
            Console.WriteLine("Uploading {0} ({1:N0} bytes)",
                                uploadfolder, fileStream.Length);
            client.BufferSize = 4 * 1024; // bypass Payload error large files
            client.UploadFile(fileStream, Path.GetFileName(uploadfolder));
        }
    }
}

Который отлично работает для одного файла. Теперь я хочу загрузить целую папку/каталог.

Кто-нибудь знает, как этого добиться?


person Francis    schedule 08.09.2016    source источник


Ответы (2)


Нет никакого волшебного способа. Вы должны перечислить файлы и загрузить их один за другим:

void UploadDirectory(SftpClient client, string localPath, string remotePath)
{
    Console.WriteLine("Uploading directory {0} to {1}", localPath, remotePath);

    IEnumerable<FileSystemInfo> infos =
        new DirectoryInfo(localPath).EnumerateFileSystemInfos();
    foreach (FileSystemInfo info in infos)
    {
        if (info.Attributes.HasFlag(FileAttributes.Directory))
        {
            string subPath = remotePath + "/" + info.Name;
            if (!client.Exists(subPath))
            {
                client.CreateDirectory(subPath);
            }
            UploadDirectory(client, info.FullName, remotePath + "/" + info.Name);
        }
        else
        {
            using (Stream fileStream = new FileStream(info.FullName, FileMode.Open))
            {
                Console.WriteLine(
                    "Uploading {0} ({1:N0} bytes)",
                    info.FullName, ((FileInfo)info).Length);

                client.UploadFile(fileStream, remotePath + "/" + info.Name);
            }
        }
    }
}

Если вам нужен более простой код, вам придется использовать другую библиотеку. Например, моя сборка WinSCP .NET может загрузить весь каталог, используя одиночный вызов Session.PutFilesToDirectory:

var results = session.PutFilesToDirectory(localPath, remotePath);
results.Check();
person Martin Prikryl    schedule 09.09.2016

Если это поможет, я перевел код на VB.NET:

Sub UploadDirectorySftp(Client As SftpClient, LocalPath As String, RemotePath As String)

    Dim subPath As String
    Dim Infos As IEnumerable(Of FileSystemInfo) =
        New DirectoryInfo(LocalPath).EnumerateFileSystemInfos()
    For Each info In Infos
        If info.Attributes.HasFlag(FileAttributes.Directory) Then
            subPath = RemotePath + "/" + info.Name
            If Not Client.Exists(subPath) Then
                Client.CreateDirectory(subPath)
            End If
            UploadDirectorySftp(Client, info.FullName, RemotePath + "/" + info.Name)
        Else
            Using filestream = New FileStream(info.FullName, FileMode.Open)
                Client.UploadFile(filestream, RemotePath + "/" + info.Name)
            End Using
        End If
    Next

End Sub

Пример использования:

Using ServerClient = New Renci.SshNet.SftpClient("host", porta, "user", "pswd")
    ServerClient.Connect()
    UploadDirectorySftp(ServerClient, "V:\aaa\", "Immagini")
    ServerClient.Disconnect()
End Using
person Marco    schedule 09.09.2020