繁体   English   中英

使用SSH.NET从SFTP服务器下载一个特定文件

[英]Download one specific file from SFTP server using SSH.NET

我试图使用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));
        }
    }

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

这就是为什么要在条件中使用foreach循环的原因。

谢谢您的帮助。

您不需要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)

但是你没有。

如果要检查文件是否存在,可以执行类似的操作...

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM