使用 SSH.NET 上传整个文件夹

问题描述 投票:0回答:3

我在 C# 2015 中使用 SSH.NET。

通过这种方法,我可以将文件上传到我的 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));
        }
    }
}

这对于单个文件来说非常有效。现在我想上传整个文件夹/目录。

现在有人如何实现这一目标吗?

c# .net ssh sftp ssh.net
3个回答
17
投票

没有什么神奇的方法。你必须枚举文件并一一上传:

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 (var 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);
            }
        }
    }
}

如果你想要更简单的代码,你将不得不使用另一个库。例如 my WinSCP .NET assembly 可以使用一次调用

Session.PutFilesToDirectory
:

上传整个目录
var results = session.PutFilesToDirectory(localPath, remotePath);
results.Check();

0
投票

我会像上面的@martin_prikryl一样,但我会在函数顶部添加以下代码,以便在不存在时可以创建目录:

string path=string.Empty;
foreach(var p in remotePath.Split('/'))
{
    path += "/" + p;
    if (!client.Exists(path))
    {
        client.CreateDirectory(path);
    }
}

-4
投票

如果有帮助,我已将代码翻译成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
© www.soinside.com 2019 - 2024. All rights reserved.