问题
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