/// <summary>
/// Download a file from the specified url and copy it to the specified path
/// </summary>
private void DownloadFile(string url, string path, long startPoint)
{
int startingPoint = Convert.ToInt32(startPoint);
try
{
//For using untrusted SSL Certificates
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(OnCheckRemoteCallback);
_Request = (HttpWebRequest)HttpWebRequest.Create(url);
_Request.AddRange(startingPoint);
if (!string.IsNullOrEmpty(LoginUsername))
{
_Request.Credentials = new NetworkCredential(LoginUsername, LoginPassword);
}
else
{
_Request.Credentials = CredentialCache.DefaultCredentials;
}
if (ProxyEnabled)
{
_Request.Proxy = new WebProxy(ProxyURL);
}
_Response = (HttpWebResponse)_Request.GetResponse();
Stream responseSteam = _Response.GetResponseStream();
if (startingPoint == 0)
{
_SaveFileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
}
else
{
_SaveFileStream = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
}
int bytesSize;
long fileSize = _Response.ContentLength;
byte[] downloadBuffer = new byte[DEF_PACKET_LENGTH];
OnProgressChanged(new DownloadProgressEventArgs(fileSize, 0, "Starting the download..."));
while ((bytesSize = responseSteam.Read(downloadBuffer, 0, downloadBuffer.Length)) > 0 && !_ExitThread)
{
if (_ExitThread)
{
break;
}
_SaveFileStream.Write(downloadBuffer, 0, bytesSize);
OnProgressChanged(new DownloadProgressEventArgs(_SaveFileStream.Length, fileSize + startingPoint, "Download in progress..."));
}
if (_ExitThread)
{
_SaveFileStream.Close();
_SaveFileStream.Dispose();
OnDownloadCompleted(new DownloadCompleteEventArgs(false, true));
return;
}
OnDownloadCompleted(new DownloadCompleteEventArgs(true, false));
}
catch (Exception ex)
{
OnDownloadError(new DownloadErrorEventArgs(ex, string.Format("Problem downloading and copying file from {0} to {1}.", url, path)));
OnDownloadCompleted(new DownloadCompleteEventArgs(false, false));
}
finally
{
if (_SaveFileStream != null)
{
_SaveFileStream.Close();
_SaveFileStream.Dispose();
}
if (_Response != null)
{
_Response.Close();
}
}
}