Monday, 14 May 2012

C# Programming : Download file from FTP server and save using c#

You are able to download file from FTP server and save to your desire location using .Net
Using FtpWebRequest and FtpWebResponse classes executing File Transfer Protocol (FTP) commands from your Web page easy. Using these classes, implementing an entire FTP client right from your Web application is now possible.
In this example we are using System.Net and System.IO namespaces.

C# Example :
Uri url = new Uri("ftp://ftp.demo.com/file1.txt");
if (url.Scheme == Uri.UriSchemeFtp)
{
    FtpWebRequest objRequest = (FtpWebRequest)FtpWebRequest.Create(url);
    //Set credentials if required else comment this Credential code
    NetworkCredential objCredential = new NetworkCredential("FTPUserName", "FTPPassword");
    objRequest.Credentials = objCredential;
    objRequest.Method = WebRequestMethods.Ftp.DownloadFile;
    FtpWebResponse objResponse = (FtpWebResponse)objRequest.GetResponse();
    StreamReader objReader = new StreamReader(objResponse.GetResponseStream());
    byte[] buffer = new byte[16 * 1024];
    int len = 0;
    FileStream objFS = new FileStream(Server.MapPath("file1.txt"), FileMode.Create, FileAccess.Write, FileShare.Read);
    while ((len = objReader.BaseStream.Read(buffer, 0, buffer.Length)) != 0)
    {
        objFS.Write(buffer, 0, len);
    }
    objFS.Close();
    objResponse.Close();
}
In this example put your URI appropriate and Set credentials if required.

VB.net Example :
Dim url As New Uri("ftp://ftp.demo.com/file1.txt")
If url.Scheme = Uri.UriSchemeFtp Then
    Dim objRequest As FtpWebRequest = DirectCast(FtpWebRequest.Create(url), FtpWebRequest)
    'Set credentials if required else comment this Credential code
    Dim objCredential As New NetworkCredential("FTPUserName", "FTPPassword")
    objRequest.Credentials = objCredential
    objRequest.Method = WebRequestMethods.Ftp.DownloadFile
    Dim objResponse As FtpWebResponse = DirectCast(objRequest.GetResponse(), FtpWebResponse)
    Dim objReader As New StreamReader(objResponse.GetResponseStream())
    Dim buffer As Byte() = New Byte(16 * 1024 - 1) {}
    Dim len As Integer = 0
    Dim objFS As New FileStream(Server.MapPath("file1.txt"), FileMode.Create, FileAccess.Write, FileShare.Read)
    len = objReader.BaseStream.Read(buffer, 0, buffer.Length)
    While len <> 0
         objFS.Write(buffer, 0, len)
         len = objReader.BaseStream.Read(buffer, 0, buffer.Length)
    End While
    objFS.Close()
    objResponse.Close()
End If

2 comments:

  1. What about if i want to download all files or do not know name of file?

    ReplyDelete
  2. For that case you need to download folder from ftp.
    That part will comes later post.
    Thanks for giving your valuable comments.

    ReplyDelete