Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download one specific file from SFTP server using SSH.NET

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.

like image 780
jan-seins Avatar asked Dec 28 '25 07:12

jan-seins


1 Answers

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.

like image 86
Martin Prikryl Avatar answered Dec 30 '25 20:12

Martin Prikryl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!