Download file from FTP server using C#

No.of Views17809
Bookmarked0 times
Downloads 
Votes0
By  RRaveen   On  15 Feb 2010 22:02:47
Tag : CSharp , Miscellaneous
Download file from FTP server using C#
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

Most of the developers asking question in message board how download load file from the FTP server using C#.

Acutlly this is easy with .NET framework , you know why  in the .NET framework 2.0 or later version.

To this we need know which class useful from the .NET Framework to do this implementation.

FtpWebRequest:http://msdn.microsoft.com/en-us/library/system.net.ftpwebrequest.aspx

FtpWebResponse:http://msdn.microsoft.com/en-us/library/system.net.ftpwebresponse.aspx

Technologies:
.NET Framework 2.0 or later version


Language:
C#

Prerequisite
Visual Studio 2005 or later version

Implementation

To this create new console project using VS IDE give name to project as FTPDownloader then we need to add a class to separate FTP related implementations. Right click on your project and then select add new item or add new class option then give the name to class as FileDownloader.

Then we need to add two using statement top of the class file to access FTP and IO classes.

{codecitation class="brush:csharp; gutter: true;" width="500px"}

using System.Net;
using System.IO;

{/codecitation}

Then write few lines of code to get list of files name from FTP server a given directory. After that we need write another method to read every file byte by byte and save in local directory.

First create a method to get list of files.

{codecitation class="brush:csharp; gutter: true;" width="600px"}

//Connects to the FTP server and request the list of available files
public List getFileList(string FTPAddress, string username, string password)
{
List files = new List();

try
{

//Create FTP request
FtpWebRequest request = FtpWebRequest.Create(FTPAddress) as FtpWebRequest;

request.Method = WebRequestMethods.Ftp.ListDirectory;
request.Credentials = new NetworkCredential(username, password);
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = false;


FtpWebResponse response = request.GetResponse() as FtpWebResponse;
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(responseStream))
{
while (!reader.EndOfStream)
{
files.Add(reader.ReadLine());
}
}

}

}
catch (Exception ex)
{
// write to log
}
return files;
}


{/codecitation}

To above method we need to give three parameters. First one is FTP server Address, second one is username and final one is password to given username to access FTP server.

Then write a method to download file and save to local directory to given file name.

{codecitation class="brush:csharp; gutter: true;" width="600px"}

public void downloadFile(string FTPAddress, string filename, string username, string password, string destFile)
{

try
{

FtpWebRequest request = FtpWebRequest.Create(FTPAddress + filename) as FtpWebRequest;
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential(username, password);
request.UsePassive = true;
request.UseBinary = false;
request.KeepAlive = false; //close the connection when done
//Streams
FtpWebResponse response = request.GetResponse() as FtpWebResponse;
Stream reader = response.GetResponseStream();

byte[] buffer = new byte[1024];
using (Stream streamFile = File.Create(destFile))
{
while (true)
{
int bytesRead = reader.Read(buffer, 0, buffer.Length);
if (bytesRead == 0)
{
break;
}
else
{
streamFile.Write(buffer, 0, bytesRead);

}
}
}


}
catch (Exception ex)
{
// write to log
}

}

{/codecitation}

Above method to read remote file and write to given local location according file name. On this method following lines of code we need to understand.

{codecitation class="brush:csharp; gutter: true;" width="600px"}

// create file sream to write in local location.

using (Stream streamFile = File.Create(destFile))
{

// check until read byte is will be 0.
while (true)
{

// read every bulk 1024  byte data to byte array.
int bytesRead = reader.Read(buffer, 0, buffer.Length);
if (bytesRead == 0)
{
break;
}
else
{

// write to file using stream.write method.
streamFile.Write(buffer, 0, bytesRead);

}
}
}

{/codecitation}

Complete code to FileDownloader class.

{codecitation class="brush:csharp; gutter: true;" width="600px"}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace DTSys.FTPDownloader
{
public class FileDownloader
{
//Connects to the FTP server and request the list of available files
public List getFileList(string FTPAddress, string username, string password)
{
List files = new List();

try
{

//Create FTP request
FtpWebRequest request = FtpWebRequest.Create(FTPAddress) as FtpWebRequest;

request.Method = WebRequestMethods.Ftp.ListDirectory;
request.Credentials = new NetworkCredential(username, password);
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = false;


FtpWebResponse response = request.GetResponse() as FtpWebResponse;
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(responseStream))
{
while (!reader.EndOfStream)
{
files.Add(reader.ReadLine());
}
}

}

}
catch (Exception ex)
{
// write to log
}
return files;
}


public void downloadFile(string FTPAddress, string filename, string username, string password, string destFile)
{

try
{

FtpWebRequest request = FtpWebRequest.Create(FTPAddress + filename) as FtpWebRequest;
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential(username, password);
request.UsePassive = true;
request.UseBinary = false;
request.KeepAlive = false; //close the connection when done
//Streams
FtpWebResponse response = request.GetResponse() as FtpWebResponse;
Stream reader = response.GetResponseStream();

byte[] buffer = new byte[1024];
using (Stream streamFile = File.Create(destFile))
{
while (true)
{
int bytesRead = reader.Read(buffer, 0, buffer.Length);
if (bytesRead == 0)
{
break;
}
else
{
streamFile.Write(buffer, 0, bytesRead);

}
}
}


}
catch (Exception ex)
{
// write to log
}

}

}
}

{/codecitation}

How incorporate/use in user project

To use in your project this class, follow the steps below.

{codecitation class="brush:csharp; gutter: true;" width="600px"}

// create instance to FileDownlaoder class.

FileDownloader fDownloader = new FileDownloader();
// get file list from the FTP server which is given remote folder.
List collectionOfFiles = fDownloader.getFileList(ftpServer, userName, password);
if (collectionOfFiles != null)
{
foreach (string fileName in collectionOfFiles)
{

// prepare the destination file path to save.
string fullPathDestionation = Path.Combine(destionationLocation, Path.GetFileNameWithoutExtension(fileName) + ".csv");

// then call download method to download every files to local directory.

fDownloader.downloadFile(ftpServer, fileName, userName, password, fullPathDestionation);
}
}

{/codecitation}

Conclusion

This article explained how to download list of files from the FTP server to save local directory and get list of files form the FTP directory

Thank you

RRaveen

Bsc,MCTS,MCDP,MCP

 
Sign Up to vote for this article
 
About Author
 
RRaveen
Occupation-Software Engineer
Company-TGS
Member Type-Gold
Location-Singapore
Joined date-03 Jun 2009
Home Page-codegain.com
Blog Page-www.codegain.com
- B.Sc. degree in Computer Science. - 4+ years experience in Visual C#.net and VB.net - Obsessed in OOP style design and programming. - Designing and developing Network security tools. - Designing and developing a client/server application for sharing files among users in a way other than FTP protocol. - Designing and implementing GSM gateway applications and bulk messaging. - Windows Mobile and Symbian Programming - Having knowledge with ERP solutions
 
 
Other popularSectionarticles
Comments
By:PaoloDate Of Posted:10/21/2010 9:50:45 AM
Paul Shafft
What do you mean remove the default web site location path ?
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top