simple code sample for sftp download?

Sep 4, 2011 at 11:32 PM

I'm sorry if this is in the help file, or somewhere else, but after digging around I couldn't find anything. I've included sample code below that I'm using. Just looking for a little guidance on how to download a file using sftpClient. The code below works great for me to get connected and get a list of files, where the code comment says "//THIS IS WHERE I WANT TO DOWNLOAD" is where i'd like to perform the download action. Again apologies if I've overlooked an example of this somewhere else.

 

        try
        {
            var connectioninfo = new KeyboardInteractiveConnectionInfo("myhost.com", 22, "root");
            connectioninfo.AuthenticationPrompt += delegate(object sender2, AuthenticationPromptEventArgs a)
            {
                foreach (var prompt in a.Prompts)
                {
                    if (prompt.Request=="Password: ")
                    {
                        prompt.Response = "password";
                    }
                }
            };
            using (var client = new SftpClient(connectioninfo))
            {
                client.Connect();
                if (client.IsConnected)
                {
                    //Response.Write("CONNECTED");
                    IEnumerable<SftpFile> thefiles = client.ListDirectory("/srv/www/simonsell-webworx.com/XML/").Where(f => f.LastAccessTime > DateTime.Now.AddDays(-3));
                    foreach (SftpFile fi in thefiles)
                    {
                        if (fi.LastWriteTime > DateTime.Now.AddDays(-3))
                        {
                            //Response.Write(fi.FullName + "<br />");
                           //THIS IS WHERE I WANT TO DOWNLOAD
                        }
                    }
                }
                else
                {
                    Response.Write("CONNECTION FAILED");
                }
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message + " " + ex.StackTrace);
        }

Sep 5, 2011 at 12:50 PM

what a difference a few hours of sleep makes! I was able to get it to work this morning. I just added this code to where I had put "THIS IS WHERE I WANT TO DOWNLOAD" and it worked perfectly.

                                FileStream thefile = new FileStream(Server.MapPath("/App_Data/" + fi.Name), FileMode.Append, FileAccess.Write, FileShare.Write);
                                client.DownloadFile(fi.FullName, thefile);
                                thefile.Close();
                                thefile.Dispose();