Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SSH.NET Upload whole folder

I use SSH.NET in C# 2015.

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?

like image 317
Francis Avatar asked Sep 08 '16 18:09

Francis


1 Answers

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

If you want a simpler code, you will have to use another library. For example my WinSCP .NET assembly can upload whole directory using a single call to Session.PutFilesToDirectory:

var results = session.PutFilesToDirectory(localPath, remotePath);
results.Check();
like image 88
Martin Prikryl Avatar answered Oct 04 '22 04:10

Martin Prikryl