A simple working code to download a file with SSH.NET library is:
using (Stream fileStream = File.Create(@"C:argetlocalpathfile.zip"))
{
sftp.DownloadFile("/source/remote/path/file.zip", fileStream);
}
See also Downloading a directory using SSH.NET SFTP in C#.
To explain, why your code does not work:
The second parameter of SftpClient.DownloadFile
is a stream to write a downloaded contents to.
You are passing in a read stream instead of a write stream. And moreover the path you are opening read stream with is a remote path, what cannot work with File
class operating on local files only.
Just discard the File.OpenRead
line and use a result of previous File.OpenWrite
call instead (that you are not using at all now):
Stream file1 = File.OpenWrite(localFileName);
sftp.DownloadFile(file.FullName, file1);
Or even better, use File.Create
to discard any previous contents that the local file may have.
I'm not sure if your localFileName
is supposed to hold full path, or just file name. So you may need to add a path too, if necessary (combine localFileName
with sDir
?)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…