2009/06/11

Download a single file from the remote FTP site (Updated)

Three approaches to download a file from FTP server: WebRequest, FtpWebRequest, and WebClient. Here are the examples:
url = "ftp://xxx.xxx.xxx.xxx/test.txt"

WebRequest
using System.Net;  //don't forget this
public string DownloadFile(string url, string username, string pw)
{
  string strResult = "";
  try
  {
    WebRequest oRequest = HttpWebRequest.Create(new Uri(url));
    oRequest.Credentials = new NetworkCredential(username, pw);
    WebResponse oResponse = oRequest.GetResponse();

    using (StreamReader sr = new StreamReader(oResponse.GetResponseStream()))
    {
      strResult = sr.ReadToEnd();
      sr.Close();
    }

    oRequest = null;
    oResponse = null;
  }
  catch (WebException wex)
  {
    //your error handling here
  }
  return strResult;
}

MS recommend us to use the FtpWebRequest class if the file is on a FTP server.
public string DownloadFile(string url, string username, string pw)
{
  string strResult = "";
  try
  {
    FtpWebRequest oFtpReq = (FtpWebRequest)WebRequest.Create(new Uri(url));
    oFtpReq.Method = WebRequestMethods.Ftp.DownloadFile;

    //set the username & password
    oFtpReq.Credentials = new NetworkCredential(username, pw);

    //There is no need to use the binary mode for a simple and small text file
    oFtpReq.UseBinary = false;

    //Add this if you get an error like this:
    //The remote server returned an error: 227 Entering Passive Mode
    oFtpReq.UsePassive = false;
    FtpWebResponse oFtpResp = (FtpWebResponse)oFtpReq.GetResponse();

    using (StreamReader sr = new StreamReader(oFtpResp.GetResponseStream()))
    {
      strResult = sr.ReadToEnd();
      sr.Close();
    }

    oFtpResp.Close();
    oFtpReq = null;
    oFtpResp = null;
  }
  catch (WebException wex)
  {
    //your error handling here
  }
  return strResult;
}

Basically, using WebClient is the same with using WebRequest.
public string DownloadFile3(string url, string username, string pw)
{
  string strResult = "";
  try
  {
    using (WebClient oWebClient = new WebClient())
    {
      oWebClient.Credentials = new NetworkCredential(username, pw);
      strResult = oWebClient.DownloadString(new Uri(url));
    }
  }
  catch (WebException wex)
  {
    //your error handling here
  }
  return strResult;
}

PS:
1.Be careful if the file size is big. If so, it's better to use byte[] to hold the stream.
2.FtpWebRequest supports resume download.

No comments:

Post a Comment