0

我正在使用 SSH.NET 从 SFTP 下载文件,这是我的代码:

string host = ConfigurationManager.AppSettings["SFTPDomain"];
string username = ConfigurationManager.AppSettings["SFTPUser"];
string password = ConfigurationManager.AppSettings["SFTPPass"];
string remoteFileName = ConfigurationManager.AppSettings["SFTPFileName"].ToString();

using (var sftp = new SftpClient(host, username, password))
{
    sftp.Connect();

    using (var file = File.OpenWrite(FilePath))
    {
        sftp.DownloadFile(remoteFileName, file);
    }

    sftp.Disconnect();
}

问题是下载了 csv 文件,但里面没有任何数据。我也更改了 remoteFile 路径,但仍然下载了包含空数据的文件。我试图检查文件是否存在使用

if (sftp.Exists(remoteFileName))
{
}

即使我用 .remoteFileName 更改它也总是返回 true "pp"

谁能帮助我我做错了什么?或者推荐我另一个库来从 SFTP 服务器下载文件。我已经尝试过 WinSCP,但我收到了 hostkey 错误,所以我尝试SshHostKeyFingerprint按照服务器教程的指导正确传递。我仍然收到主机密钥错误。是否有任何简单的库我只需要从 SFTP 下载文件?

4

2 回答 2

3

我见过同样的问题。使用 SSH.NETScpClient而不是SftpClient为我工作。这是一个插入式替换:

using (ScpClient client = new ScpClient(host, username, password))
{
    client.Connect();

    using (Stream localFile = File.Create(localFilePath))
    {
         client.Download(remoteFilePath, localFile);
    }
}

使用 ScpClient,您只能获得上传/下载功能,而不是 SFTP 的许多附加功能,但这对于您的用例可能已经足够了。

于 2018-06-13T19:18:47.850 回答
1

尝试使用:

using (Stream file = File.OpenWrite(FilePath))
{
    sftp.DownloadFile(remoteFileName, file);
}

在本地保存之前,您需要从远程服务器读取流。

于 2017-12-01T15:47:36.403 回答