[C#] Download File Supporting Resume

Simple function in C# that allows to download a file from the internet and supports to resume the download, using HttpWebRequest/HttpWebResponse and FileStream

public static void downloadFile(string sourceURL, string destinationPath)
{
long fileSize = 0;
int bufferSize = 1024;
bufferSize *= 1000;
long existLen = 0;
System.IO.FileStream saveFileStream;
if (System.IO.File.Exists(destinationPath))
{
System.IO.FileInfo destinationFileInfo = new System.IO.FileInfo(destinationPath);
existLen = destinationFileInfo.Length;
}
if (existLen > 0)
saveFileStream = new System.IO.FileStream(destinationPath,
System.IO.FileMode.Append,
System.IO.FileAccess.Write,
System.IO.FileShare.ReadWrite);
else
saveFileStream = new System.IO.FileStream(destinationPath,
System.IO.FileMode.Create,
System.IO.FileAccess.Write,
System.IO.FileShare.ReadWrite);
System.Net.HttpWebRequest httpReq;
System.Net.HttpWebResponse httpRes;
httpReq = (System.Net.HttpWebRequest) System.Net.HttpWebRequest.Create(sourceURL);
httpReq.AddRange((int) existLen);
System.IO.Stream resStream;
httpRes = (System.Net.HttpWebResponse) httpReq.GetResponse();
resStream = httpRes.GetResponseStream();
fileSize = httpRes.ContentLength;
int byteSize;
byte[] downBuffer = new byte[bufferSize];
while ((byteSize = resStream.Read(downBuffer, 0, downBuffer.Length)) > 0)
{
saveFileStream.Write(downBuffer, 0, byteSize);
}
}
view raw DownloadFile.cs hosted with ❤ by GitHub

What about you, how do you downloading files using C# ?

Tagged: , ,

Leave a Reply :

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: