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
|