如何通过Web服务下载文件?

时间:2017-02-06 10:48:07

标签: c# web-services asmx

如何通过网络服务下载文件?

我试过这个,但他的应用程序抛出了这个错误。

  

服务器无法在发送http标头后添加标头。

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

        byte[] data = req.DownloadData(serverPath);
        response.BinaryWrite(data);
        //response.End();
        HttpContext.Current.ApplicationInstance.CompleteRequest();
    }
    catch (Exception ex)
    {

        throw ex;
    }
}

1 个答案:

答案 0 :(得分:0)

同步下载文件:

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

以异步方式下载文件:

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!");
}