ASP.NET Download a SFTP file using the browser

c# asp.net sftp

1018 观看

1回复

95 作者的声誉

I was trying to download a SFTP file(.csv) using C# and asp.net, 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


0

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))
        {
            sftp.Connect();
            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.Clear();
        Response.AddHeader("Content-Disposition", "attachment;filename=" + fileInfo.Name);
        Response.AddHeader("Content-Length", fileInfo.Length.ToString());
        Response.ContentType = "text/csv";
        Response.Flush();
        Response.WriteFile(fileInfo.FullName);
        Response.End();
作者: Alessandro Sanfilippo 发布者: 2017 年 12 月 28 日
32x32