Here I will post problems I and my colleagues met and solutions we found.

Sunday, August 17, 2008

Getting File size using ContentLength when downloading from FTP server

There is a property ContentLength of class FtpWebResponse. When I wrote the code similar to example, provided by MSDN, this property always returned -1. As it turned out, it was important to read fine print. I had to set method to GetFileSize to get proper value. So, what I got in result that worked was this:

// Get file size
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(_uri);
request.Method = WebRequestMethods.Ftp.GetFileSize;
request.Credentials = credential;
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
long fileSize = response.ContentLength;

// Download file
request = (FtpWebRequest)WebRequest.Create(_uri);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = credential;
response = (FtpWebResponse)request.GetResponse();


And then getting stream from response etc.

2 comments:

Anonymous said...

Thanks man, that really helped me. I didn't get it why no ContentLength was received nor why it didn't download.

Peace up

Anonymous said...

Thanx a mil... have been looking for this a whole evening...