2017-02-06 3 views
0

Wie wird die Datei über den Webservice heruntergeladen?Wie kann ich eine Datei über einen Webservice herunterladen?

Ich habe versucht, aber er Anwendung wirft diesen Fehler.

Der Server kann keine Header hinzufügen, nachdem HTTP-Header gesendet wurden.

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; 
    } 
} 

Antwort

0

Um die Datei Synchrone herunterladen:

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

die Datei asynchron herunter:

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

Dankes- die Lösung gearbeitet. –

Verwandte Themen