【问题标题】:Download one specific file from SFTP server using SSH.NET使用 SSH.NET 从 SFTP 服务器下载一个特定文件
【发布时间】:2017-02-04 03:57:03
【问题描述】:

我正在尝试使用 SSH.NET 从服务器上仅下载一个文件。

到目前为止,我有这个:

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

我的问题是我不知道如何用字符串@"/home/xymon/data/hist/allevents" 构造SftpFile

这就是为什么我使用带有条件的foreach 循环的原因。

感谢您的帮助。

【问题讨论】:

    标签: c# .net ssh sftp ssh.net


    【解决方案1】:

    您不需要SftpFile 来调用SftpClient.DownloadFile。该方法仅采用普通路径:

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

    像这样使用它:

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

    如果你真的需要SftpFile,你可以使用SftpClient.Get 方法:

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

    但你没有。

    【讨论】:

    • .NET 4.8 如果您在客户端期间遇到异常,使用将创建一个 0 字节文件。DownloadFile... 可能不是您想要的。
    【解决方案2】:

    如果你想检查文件是否存在,你可以这样做......

        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
                {
                    //...
                }
            }
        }
    

    【讨论】:

    • @DriveByDownvoter:你真的知道如何鼓励新人,不是吗?难怪他突然出现然后又突然退出。我骂你是个懒惰的懦夫。没有建设性批评的否决票?可耻。
    • 不知道为什么它被否决了。我唯一注意到的一个问题是 _pacRemoteDirectory 没有声明。这并不难解决。
    最近更新 更多