2

I want to download file from FTP and open a download/save prompt in user's web browser, when the user clicks on a download button on ASP.NET C# page.

string strDownloadURL = System.Configuration.ConfigurationSettings.AppSettings["DownloadURL"];
string HostName = System.Configuration.ConfigurationSettings.AppSettings["HostName"];
string strUser = System.Configuration.ConfigurationSettings.AppSettings["BasicAuthenticationUser"];
string strPWD = System.Configuration.ConfigurationSettings.AppSettings["BasicAuthenticationPWD"];

FtpWebRequest request = (FtpWebRequest)WebRequest.Create(HostName + strFile);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential(strUser, strPWD);
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = false;

FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
string fileName = @"c:\temp\" + strFile + "";
Directory.CreateDirectory(Path.GetDirectoryName(fileName));
FileStream file = File.Create(fileName);
byte[] buffer = new byte[2 * 1024];
int read;
while ((read = responseStream.Read(buffer, 0, buffer.Length)) > 0) { file.Write(buffer, 0, read); }
file.Close();
responseStream.Close();
response.Close();
Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
Jitender Bisht
  • 125
  • 1
  • 2
  • 13

2 Answers2

0

So, assuming you're writing the FTP request's response stream down to the ASP.NET response stream, and want to trigger the download dialog in the browser, you'll want to set the Content-Disposition header in the response.

// note: since you are writing directly to client, I removed the `file` stream
// in your original code since we don't need to store the file locally...
// or so I am assuming
Response.AddHeader("content-disposition", "attachment;filename=" + strFile);

byte[] buffer = new byte[2 * 1024];
int read;
while ((read = responseStream.Read(buffer, 0, buffer.Length)) > 0) 
{ 
   Response.OutputStream.Write(buffer, 0, read);
}

responseStream.Close();
response.Close();
Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
moribvndvs
  • 42,191
  • 11
  • 135
  • 149
0

The answer by @moribvndvs is correct. But the code can be way simpler with use of WebClient.OpenRead and Stream.CopyTo:

var filename = "file.zip";
Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);

var client = new WebClient();
client.Credentials = new NetworkCredential("username", "password");
var url = "ftp://ftp.example.com/remote/path/" + filename;
using (var ftpStream = client.OpenRead(url))
{
    ftpStream.CopyTo(Response.OutputStream);
}

(where Response is ASP.NET HttpResponse).

See also Upload and download a file to/from FTP server in C#/.NET.

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992