Download files from SFTP with SSH.NET library

前端 未结 5 1570
眼角桃花
眼角桃花 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?)

    0 讨论(0)
  • 2020-12-13 04:31

    Without you providing any specific error message, it's hard to give specific suggestions.

    However, I was using the same example and was getting a permissions exception on File.OpenWrite - using the localFileName variable, because using Path.GetFile was pointing to a location that obviously would not have permissions for opening a file > C:\ProgramFiles\IIS(Express)\filename.doc

    I found that using System.IO.Path.GetFileName is not correct, use System.IO.Path.GetFullPath instead, point to your file starting with "C:\..."

    Also open your solution in FileExplorer and grant permissions to asp.net for the file or any folders holding the file. I was able to download my file at that point.

    0 讨论(0)
  • 2020-12-13 04:34

    This solves the problem on my end.

    var files = sftp.ListDirectory(remoteVendorDirectory).Where(f => !f.IsDirectory);
    
    foreach (var file in files)
    {
        var filename = $"{LocalDirectory}/{file.Name}";
        if (!File.Exists(filename))
        {
            Console.WriteLine("Downloading  " + file.FullName);
            var localFile = File.OpenWrite(filename);
            sftp.DownloadFile(file.FullName, localFile);
        }
    }
    
    0 讨论(0)
  • 2020-12-13 04:49

    While the example works, its not the correct way to handle the streams...

    You need to ensure the closing of the files/streams with the using clause.. Also, add try/catch to handle IO errors...

           public void DownloadAll()
        {
            string host = @"sftp.domain.com";
            string username = "myusername";
            string password = "mypassword";
    
            string remoteDirectory = "/RemotePath/";
            string localDirectory = @"C:\LocalDriveFolder\Downloaded\";
    
            using (var sftp = new SftpClient(host, username, password))
            {
                sftp.Connect();
                var files = sftp.ListDirectory(remoteDirectory);
    
                foreach (var file in files)
                {
                    string remoteFileName = file.Name;
                    if ((!file.Name.StartsWith(".")) && ((file.LastWriteTime.Date == DateTime.Today))
    
                        using (Stream file1 = File.OpenWrite(localDirectory + remoteFileName))
                        { 
                            sftp.DownloadFile(remoteDirectory + remoteFileName, file1);
                        }
                }
    
            }
        }
    
    0 讨论(0)
  • 2020-12-13 04:50

    My version of @Merak Marey's Code. I am checking if files exist already and different download directories for .txt and other files

            static void DownloadAll()
        {
            string host = "xxx.xxx.xxx.xxx";
            string username = "@@@";
            string password = "123";string remoteDirectory = "/IN/";
            string finalDir = "";
            string localDirectory = @"C:\filesDN\";
            string localDirectoryZip = @"C:\filesDN\ZIP\";
            using (var sftp = new SftpClient(host, username, password))
            {
                Console.WriteLine("Connecting to " + host + " as " + username);
                sftp.Connect();
                Console.WriteLine("Connected!");
                var files = sftp.ListDirectory(remoteDirectory);
    
                foreach (var file in files)
                {
    
                    string remoteFileName = file.Name;
    
                    if ((!file.Name.StartsWith(".")) && ((file.LastWriteTime.Date == DateTime.Today)))
                    { 
    
                        if (!file.Name.Contains(".TXT"))
                        {
                            finalDir = localDirectoryZip;
                        } 
                        else 
                        {
                            finalDir = localDirectory;
                        }
    
    
                        if (File.Exists(finalDir  + file.Name))
                        {
                            Console.WriteLine("File " + file.Name + " Exists");
                        }else{
                            Console.WriteLine("Downloading file: " + file.Name);
                              using (Stream file1 = File.OpenWrite(finalDir + remoteFileName))
                        {
                            sftp.DownloadFile(remoteDirectory + remoteFileName, file1);
                        }
                        }
                    }
                }
    
    
    
                Console.ReadLine();
    
            }
    
    0 讨论(0)
提交回复
热议问题