Download files from SFTP with SSH.NET library

前端 未结 5 1574
眼角桃花
眼角桃花 2020-12-13 04:08
string host = @\"ftphost\";
string username = \"user\";
string password = \"********\";
string localFileName  = System.IO.Path.GetFileName(@\"localfilename\");
strin         


        
5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-13 04:24

    A simple working code to download a file with SSH.NET library is:

    using (Stream fileStream = File.Create(@"C:\target\local\path\file.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?)

提交回复
热议问题