Download one specific file from SFTP server using SSH.NET

11,637

Solution 1

You do not need the SftpFile to call SftpClient.DownloadFile. The method takes a plain path only:

/// <summary>
/// Downloads remote file specified by the path into the stream.
/// </summary>
public void DownloadFile(string path, Stream output, Action<ulong> downloadCallback = null)

Use it like:

using (Stream fileStream = File.OpenWrite(Path.Combine(str_target_dir, "allevents")))
{
    client.DownloadFile("/home/xymon/data/hist/allevents", fileStream);
}

Had you really needed the SftpFile, you could use SftpClient.Get method:

/// <summary>
/// Gets reference to remote file or directory.
/// </summary>
public SftpFile Get(string path)

But you do not.

Solution 2

If you want to check if the file exists, you can do something like that...

    public void DownloadFile(string str_target_dir)
    {
        using (var client = new SftpClient(host, user, pass))
        {
            client.Connect();
            var file = client.ListDirectory(_pacRemoteDirectory).FirstOrDefault(f => f.Name == "Name");
            if (file != null)
            {
                using (Stream fileStream = File.OpenWrite(Path.Combine(str_target_dir, file.Name)))
                {
                    client.DownloadFile(file.FullName, fileStream);
                }
            }
            else
            {
                //...
            }
        }
    }
Share:
11,637
jan-seins
Author by

jan-seins

Updated on June 04, 2022

Comments

  • jan-seins
    jan-seins almost 2 years

    I am trying to download only one file using SSH.NET from a server.

    So far I have this:

    using Renci.SshNet;
    using Renci.SshNet.Common;
    ...
    public void DownloadFile(string str_target_dir)
        {
            client.Connect();
            if (client.IsConnected)
            {
                var files = client.ListDirectory(@"/home/xymon/data/hist");
                foreach (SftpFile file in files)
                {
                    if (file.FullName== @"/home/xymon/data/hist/allevents")
                    {
                        using (Stream fileStream = File.OpenWrite(Path.Combine(str_target_dir, file.Name)))
                        {
                            client.DownloadFile(file.FullName, fileStream);
                        }
                    }
                }
            }
            else
            {
                throw new SshConnectionException(String.Format("Can not connect to {0}@{1}",username,host));
            }
        }
    

    My problem is that I don't know how to construct the SftpFile with the string @"/home/xymon/data/hist/allevents".

    That's the reason, why I use the foreach loop with the condition.

    Thanks for the help.