private void Download(object startPoint) { try { // Put the object argument into an int variable int startPointInt = Convert.ToInt32(startPoint); // Create a request to the file we are downloading webRequest = (HttpWebRequest)WebRequest.Create((string)txtUrl.Text); // Set the starting point of the request webRequest.AddRange(startPointInt); // Set default authentication for retrieving the file webRequest.Credentials = CredentialCache.DefaultCredentials; // Retrieve the response from the server webResponse = (HttpWebResponse)webRequest.GetResponse(); // Ask the server for the file size and store it Int64 fileSize = webResponse.ContentLength; // Open the URL for download strResponse = webResponse.GetResponseStream(); // calculate the TargetFile String sTargetFile = txtPath.Text; if (Directory.Exists(txtPath.Text)) { String sFileName = Path.GetFileName(txtUrl.Text); sTargetFile = Path.Combine(sTargetFile, sFileName); } if (File.Exists(sTargetFile)) { try { File.Delete(sTargetFile); } catch (Exception) { string alternativeFileName = DI.config.TempFileNameInTempDirectory + "_" + Path.GetFileName(sTargetFile); DI.log.info("In Donwnload could not create file :{0}, so downloding into {1} instead", sTargetFile, alternativeFileName); sTargetFile = alternativeFileName; } } // Create a new file stream where we will be saving the data (local drive) strLocal = startPointInt == 0 ? new FileStream(sTargetFile, FileMode.Create, FileAccess.Write, FileShare.None) : new FileStream(sTargetFile, FileMode.Append, FileAccess.Write, FileShare.None); // It will store the current number of bytes we retrieved from the server int bytesSize; // A buffer for storing and writing the data retrieved from the server var downBuffer = new byte[2048]; // Loop through the buffer until the buffer is empty while ((bytesSize = strResponse.Read(downBuffer, 0, downBuffer.Length)) > 0) { // Write the data from the buffer to the local hard drive strLocal.Write(downBuffer, 0, bytesSize); // Invoke the method that updates the O2Form's label and progress bar Invoke(new UpdateProgessCallback(UpdateProgress), new object[] { strLocal.Length, fileSize + startPointInt }); if (goPause) { break; } } // invoke completed callback if (dCallbackWhenCompleted != null) { dCallbackWhenCompleted.Invoke(sTargetFile); } } catch (Exception ex) { string message = string.Format("in Download: {0} (for request:{1})", ex.Message, txtUrl.Text); lblProgress.invokeOnThread(() => { lblProgress.Text = message; lblProgress.ForeColor = Color.Red; }); DI.log.error(message); } finally { // When the above code has ended, close the streams if (strResponse != null) { strResponse.Close(); } if (strLocal != null) { strLocal.Close(); } } // close O2Form if required if (cbCloseWindowWhenDownloadComplete.Checked) { if (Parent != null && (Parent.GetType().Name == "Form" || Parent.GetType().Name == "GenericDockContent")) { O2Forms.executeMethodThreadSafe(Parent, "Close"); } //().Close(); //this.Parent } }