Skip to content

Instantly share code, notes, and snippets.

@barwis
Forked from nboubakr/DownloadFile.cs
Last active August 29, 2015 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barwis/15e476fee42c678a922f to your computer and use it in GitHub Desktop.
Save barwis/15e476fee42c678a922f to your computer and use it in GitHub Desktop.
Simple function in C# to download a file from the internet, supports to resume the download.
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);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment