Friday, May 16, 2008

FTP file download with C#

FTP file download with C# is a piece of cake as C# provides everything at our fingertips. As long as we have "using System.Net;" line at top... we are good.


Here we use FtpWEbRequest, FtpWebResponse (provided in System.Net namespace) and FileStream (System.IO) to get it done. I have done my best to provide as much as comments that would fit in a code! And the code is so simple so i should waste time writing an essay here... ;)


You can download my sample visual studio solution (c# project) for FTP Uploads/Downloads at my web site [www.thekalana.net\downloads.html]


Please note that; this code does not provide functionality to manipulate connecting via a proxy server. Still this will work with in Visual Studio since VS uses the proxy settings in IE. But u should explicitly use proxy manipulations in order to deploy the app. U can find code for capturing proxy settings from IE, in a proceeding post or at my web site [www.thekalana.net\downloads.html].


Sample Source Code :

///

/// Method for downloading a file to the specified FTP Server

///

public void Download(string localpath, string remotepath)

{

FtpWebRequest reqFTP;

try

{

//localpath = <>,

//remotepath = <>

//----- can use this block if neccesary to implement uploading with sub directory structure.

//string derivedpath = remotepath.Replace("/","_"); //remove all backslashes in remotepath and replace with underscore

//MessageBox.Show(derivedpath);

//-----

// Open file stream (System.IO.FileStream) to read the file to be downloaded

FileStream outputStream = new FileStream(localpath + "\\" + remotepath, FileMode.Create);

// Create FtpWebRequest object from the Uri

reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + remotepath));

// FTP Command to be executed

reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;

// Data tranfer type

reqFTP.UseBinary = true;

// Provide WebPermission Credintials

reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);

FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();

Stream ftpStream = response.GetResponseStream();

long cl = response.ContentLength;

// Set buffer size

int bufferSize = 2048;

int readCount;

byte[] buffer = new byte[bufferSize];

// Read from the stream at above mentioned buffer size rate

readCount = ftpStream.Read(buffer, 0, bufferSize);

// till stream download ends

while (readCount > 0)

{

outputStream.Write(buffer, 0, readCount);

readCount = ftpStream.Read(buffer, 0, bufferSize);

}

// Close ftp stream

// Close file stream

// Close ftp response

ftpStream.Close();

outputStream.Close();

response.Close();

}

catch (Exception ex)

{

MessageBox.Show(ex.Message);

}

}

No comments: