batwing
batwing

Reputation: 247

Download from FTP server to client computer

I'm working on ASP.NET project and I need a function where a user downloads a file from FTP server and saved to his/her local machine. The files are in different FTP server and the ASP.NET project is hosted in different server. So to download, I passed the server address and FTP credentials. It works when I runs the project on localhost, but when I upload the project to server and try to download from the hosted site, the files doesn't download and save to my pc.

This my code below

 string inputfilepath = @"C:\Temp\"+_filename;
 string ftphost = "[email protected]:3131";
 string ftpfilepath = _filename;

 string ftpfullpath = "ftp://" + ftphost +"/"+ ftpfilepath;

 using (WebClient request = new WebClient())
 {
      request.Credentials = new NetworkCredential("username", "password");
      byte[] fileData = request.DownloadData(ftpfullpath);

      Directory.CreateDirectory(Path.GetDirectoryName(inputfilepath));

      using (FileStream file = File.Create(inputfilepath))
      {
           file.Write(fileData, 0, fileData.Length);
           file.Close();
      }

      ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('Receipt downloaded and saved at C:\\\\Temp\\\\BankTransfer.');", true);
 }

Upvotes: 1

Views: 683

Answers (2)

Graham
Graham

Reputation: 639

The (hosted) web server does not have access to the remote client (your PC). When you are saving, you are saving to the web server's local C drive. If you want them on your C drive, you are going to need to do one of two things:

  1. Take the file you downloaded from the FTP site (which now sits on the web server) and deliver back to the client via HTTP. This means you aren't sending the file via FTP (with all the pros and cons that come with that), but you also are sharing the FTP credentials. You have no control of where the client saves the files.
  2. Instead of downloading the file to the web server, you can just provide a link with the ftp protocol ('ftp://...'), including credentials. This exposes your credentials, however it avoid having twice the bandwidth to the web server (because the client downloads it direct), and prevents you form having to manage a file now sitting on the server. It also avoids and security risks (for the web server) if the file could be compromised. You have no control of where the client saves the files.

Upvotes: 2

Martheen
Martheen

Reputation: 5644

After saving the file on your server, return it as a file to your client's browser. You don't mention your framework so here's how to do it on WebForm and MVC. Note that you can't decide where to save the file on their computer, it's their decision whether to save or not and where.

Upvotes: 2

Related Questions