Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Http client Downloader for Retry(Palmer lib)/Resume download requests enabled.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Palmer;
namespace ConsoleApplication1
{
internal class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Starting download.... ");
try
{
DownloadFile("https://github.com/MitchDenny/Palmer/archive/master.zip", "C:\\Temp\\packages.zip");
}
catch (Exception ex)
{
if (!string.Equals(ex.Message, "Stack Empty.", StringComparison.InvariantCultureIgnoreCase))
{
Console.WriteLine("========= Error ==========");
Console.WriteLine("{0}{1}{1} Inner Exception: {1} {2}", ex.Message, Environment.NewLine,
ex.InnerException.ToString());
}
}
Console.WriteLine("Press enter key to exit.. ");
Console.Read();
}
public static bool DownloadFile(string url, string filepath)
{
WebClient client = new WebClient();
ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, errors) =>
{ return true; };
// Add a user agent header in case the
// requested URI contains a query.
int count = 1;
bool result = true;
Retry.On<Exception>().For(3).With(context =>
{
try
{
client.Headers.Add("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
client.OpenRead(url);
FileInfo finfo = null;
if (File.Exists(filepath))
{
finfo = new FileInfo(filepath);
if (client.ResponseHeaders != null &&
finfo.Length >= Convert.ToInt64(client.ResponseHeaders["Content-Length"]))
{
File.Delete(filepath);
}
}
DownloadFileWithResume(url, filepath);
// Refresh the file content size
finfo = finfo ?? new FileInfo(destinationFilePath);
if (finfo.Length == Convert.ToInt64(client.ResponseHeaders["Content-Length"]))
{
result = true;
Console.WriteLine("Download success!!!");
}
else
{
result = false;
throw new WebException("Download interrupted. Retrying download.. ");
}
}
catch (Exception ex)
{
Console.WriteLine("Error: {0} {1}", ex.Message, Environment.NewLine);
Console.WriteLine("Download inturrpted retry({0}).. in 5 seconds", count++);
System.Threading.Thread.Sleep(5000);
throw;
}
});
return false;
}
private static void DownloadFileWithResume(string sourceUrl, string destinationPath)
{
long existLen = 0;
System.IO.FileStream saveFileStream;
if (System.IO.File.Exists(destinationPath))
{
System.IO.FileInfo fINfo =
new System.IO.FileInfo(destinationPath);
existLen = fINfo.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 httpWebRequest;
System.Net.HttpWebResponse httpWebResponse;
httpWebRequest = (System.Net.HttpWebRequest) System.Net.HttpWebRequest.Create(sourceUrl);
httpWebRequest.AddRange((int) existLen);
System.IO.Stream smRespStream;
httpWebResponse = (System.Net.HttpWebResponse) httpWebRequest.GetResponse();
smRespStream = httpWebResponse.GetResponseStream();
var abc = httpWebRequest.Timeout;
smRespStream.CopyTo(saveFileStream);
saveFileStream.Close();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment