Resuming broken file download with FtpWebRequest class

This post is valid for .Netframeworks 2.0

When we are downloading a largeĀ file from ftp site and connection got broken in between, on next attempt you would be interested in downloading the rest of the file content instead of full file. FtpWebRequest class have a nice way to meet this requirement. You could use the FtpWebRequest.ContentOffset property to specify the starting position for file to download. See code example below

Following is the code for downloading the file

public static void ResumeFtpFileDownload(Uri sourceUri, string destinationFile)
FileInfo file = new FileInfo(destinationFile);
FileStream localfileStream ;
FtpWebRequest request = WebRequest.Create(sourceUri) as FtpWebRequest;
request.Method = WebRequestMethods.Ftp.DownloadFile;
if (file.Exists)
request.ContentOffset = file.Length;
localfileStream = new FileStream(destinationFile, FileMode.Append, FileAccess.Write);
localfileStream = new FileStream(destinationFile, FileMode.Create, FileAccess.Write);
WebResponse response = request.GetResponse();
Stream responseStream = response.GetResponseStream();
byte[] buffer = new byte[1024];
int bytesRead = responseStream.Read(buffer, 0, 1024);
while (bytesRead != 0)
localfileStream.Write(buffer, 0, bytesRead);
bytesRead = responseStream.Read(buffer, 0, 1024);
responseStream .Close();

This posting is provided "AS IS" with no warranties, and confers no rights