使用SSH.NET下载时文件为空

时间:2014-10-07 02:25:51

标签: c# .net sftp ssh.net

我使用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))
{
}

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

任何人都可以帮助我,我做错了吗?或者推荐我另一个库从SFTP服务器下载文件。我尝试过WinSCP,但是我收到了hostkey错误,因此我尝试在服务器tutorial的指导下传递正确的SshHostKeyFingerprint。我仍然收到hostkey错误。是否有任何简单的库我只需要从SFTP下载文件?

2 个答案:

答案 0 :(得分:2)

我见过同样的问题。使用SSH.NET ScpClient代替SftpClient为我工作。这是替代品:

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

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

使用ScpClient,您只能获得上传/下载功能,而不是SFTP的许多其他功能,但这可能足以满足您的使用需求。

答案 1 :(得分:1)

尝试使用:

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

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

相关问题