Swornim Nepal Swornim Nepal - 4 years ago 119
C# Question

How to download file via a web service?

How to download file via web service ?

I have Tried this but he application throws this error.

Server cannot add headers after http headers have been sent.

public static void StartDownload(string path, string attachmentName)
string serverPath = HostingEnvironment.MapPath(path);
WebClient req = new WebClient();
HttpResponse response = HttpContext.Current.Response;
response.Buffer = true;
response.AddHeader("Content-Type", "application/octet-stream");
response.AddHeader("Content-Disposition", "attachment;filename=\"" + attachmentName + "\"");

byte[] data = req.DownloadData(serverPath);
catch (Exception ex)

throw ex;

Answer Source

To download the File Synchronously:

WebClient webClient = new WebClient();
webClient.DownloadFile("example.com/myfile.txt", @"c:\myfile.txt");

To download the File Asynchronously:

private void btnDownload_Click(object sender, EventArgs e)
  WebClient webClient = new WebClient();
  webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
  webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
  webClient.DownloadFileAsync(new Uri("example.com/myfile.txt"), @"c:\myfile.txt");

private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
  progressBar.Value = e.ProgressPercentage;

private void Completed(object sender, AsyncCompletedEventArgs e)
  MessageBox.Show("Download completed!");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download