Thursday, August 10, 2006

FTP in .Net 2.0

So I needed to write a simple function that would download a file from an Ftp location. After googling a little, I found MSN's sample code for FTP using the new FTP classes in 2.0. Here is a link to the Microsoft Download Page. After testing it out and changing the code to my needs, it worked pretty good, except that it only worked for text files. Binary files were being downloaded but the data was corrupt. I tried different things to get it to work like using a BinaryReader and Writer but I kept getting a corrupt file. Finally, I got it to work by including a single line:

ftpRequest.UseBinary = true;

So here is a basic skeleton of how to download a binary file from an FTP location:

//Create the Request Object

FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create("the FTP URI");
ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
ftpRequest.UseBinary = true;

//Now we create a response object and ge the response stream

FtpWebResponse ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
Stream responseStream = ftpResponse.GetResponseStream();

//Create the destination File

FileStream DestFile = new FileStream("your file name here", FileMode.OpenOrCreate, FileAccess.ReadWrite);

//Reading the response stream and writing it to the destination file

try
{
byte[] myBuffer = new byte[2048];
int stream= 0;
do
{
stream= responseStream.Read(myBuffer , 0, myBuffer .Length);
DestFile.Write(myBuffer , 0, stream);
}
while (!(stream== 0));
}
catch (Exception ex)
{
//handle your exception here
finally
{
DestFile.Close();
}

If the method returns something, you could return the FtpCode:

return ftpResponse.StatusCode;

I Guess the file writing part could still be implemented using the BinaryReader and Writer objects, but this way worked out for me.