SSH.NET上传整个文件夹 [英] SSH.NET Upload whole folder

查看:340
本文介绍了SSH.NET上传整个文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I use SSH.NET in C# 2015.

通过这种方法,我可以将文件上传到我的SFTP服务器.

With this method I can upload a file to my SFTP server.

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

最适合单个文件.现在,我要上传整个文件夹/目录.

Which works perfectly for a single file. Now I want to upload a whole folder/directory.

现在有人要实现这一目标吗?

Does anybody now how to achieve this?

推荐答案

没有神奇的方法.您必须枚举文件并一一上传:

There's no magical way. You have to enumerate the files and upload them one-by-one:

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

这篇关于SSH.NET上传整个文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆