File empty when downloaded using SSH.NET

江枫思渺然 提交于 2019-12-12 02:06:01

问题


I am using SSH.NET to download file from the SFTP and here is my code:

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

The problem is that the file which is csv is downloaded but it does not have any data inside. I changed the remoteFile path as well but still the file is downloaded with null data inside. I tried to check if file exists using

if (sftp.Exists(remoteFileName))
{
}

It always return true even if I change the remoteFileName with "pp".

Can anyone help me what I am doing wrong? Or recommend me another other library to download file from SFTP server. I have tried WinSCP but I am getting hostkey error so I tried to pass correct SshHostKeyFingerprint as guided by the server tutorial. Still I get the hostkey error. Is there any simple library i just need to download file from the SFTP?


回答1:


I've seen the same issue. Using SSH.NET's ScpClient instead of SftpClient worked for me. It's a drop-in replacement:

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

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

With ScpClient you only get upload/download functionality instead of the many additional features of SFTP, but this may be good enough for your use-case.




回答2:


Try using:

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

You need to read the stream from the remote server before saving locally.



来源:https://stackoverflow.com/questions/26227676/file-empty-when-downloaded-using-ssh-net

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!