ASP.NET Download a SFTP file using the browser

c# sftp

1018 观看


95 作者的声誉

I was trying to download a SFTP file(.csv) using C# and, but all the examples needs me to have a remote file directory.

For this case, I need the browser to download the file, not me to put in the the directory, since the browser(client) will not have access to put files directly into a directory.

Have, anyone done this before?

I was trying to use SSH.NET, but didnt find a way to do it.

作者: Alessandro Sanfilippo 的来源 发布者: 2017 年 12 月 27 日

回应 1


95 作者的声誉


Resolved this, by moving the file to my server using SFTP and then downloading the file normaly.

 string host = @"host";
        string username = "user";
        string password = "pass";
        string remoteDirectory = "/remote";

        string localDirectory = Server.MapPath(@"\pdf\");

        using (var sftp = new SftpClient(host, username, password))
            var files = sftp.ListDirectory(remoteDirectory);

            foreach (var file in files)
                string remoteFileName = file.Name;
                if (remoteFileName == "APADEAATTT.csv")

                    using (Stream file1 = File.OpenWrite(localDirectory + "APADEAATTT.csv"))
                        sftp.DownloadFile(remoteDirectory + "APADEAATTT.csv", file1);


        FileInfo fileInfo = new FileInfo(localDirectory+"APADEAATTT.csv");
        Response.AddHeader("Content-Disposition", "attachment;filename=" + fileInfo.Name);
        Response.AddHeader("Content-Length", fileInfo.Length.ToString());
        Response.ContentType = "text/csv";
作者: Alessandro Sanfilippo 发布者: 2017 年 12 月 28 日