How to show progress in a webpage while downloading a file from another server ASP.NET

Web-E picture Web-E · Nov 25, 2011 · Viewed 8.1k times · Source

In one of my webpage, the controls are based on values specified in some xml files in another remote server.So I need to download and parse them at page_load() and display the controls.The problem is the xml files are quite large and take lots of time. So I want to download the xml files using webclient.DownloadFileAsync() method and show the information as how much bytes downloaded.

I have written code to download the files, but don't know how to update the page on DownloadProgressChanged event.I think it require ajax methods.Kindly guide me how to do that.

aspx page

<form id="form1" runat="server">   
</asp:ScriptManager>
<div>       
  <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
   <br />            
  <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</div>
</form>

Code behind (Thanks to another stackoverflow question)

public partial class _Default : System.Web.UI.Page
{
     protected void Page_Load(object sender, EventArgs e)
    {
    }
    private Queue<string> _downloadUrls = new Queue<string>();

   private void downloadFile(IEnumerable<string> urls)
    {
        foreach (var url in urls)
        {
            _downloadUrls.Enqueue(url);
        }
        // Starts the download
       Label1.Text = "Downloading...";
       DownloadFile();
    }

private void DownloadFile()
{
    if (_downloadUrls.Any())
    {
        WebClient client = new WebClient();
        client.UseDefaultCredentials = true;
        client.DownloadProgressChanged += client_DownloadProgressChanged;
        client.DownloadFileCompleted += new     System.ComponentModel.AsyncCompletedEventHandler(client_DownloadFileCompleted);

        var url = _downloadUrls.Dequeue();
        string FileName = url.Substring(url.LastIndexOf("/") + 1,
                    (url.Length - url.LastIndexOf("/") - 1));

        client.DownloadFileAsync(new Uri(url), Server.MapPath(".") + "\\" + FileName);
        //lblFileName.Text = url;
        return;
    }
    // End of the download
    Label1.Text = "Download Complete";
 }

 void client_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
 {
    DownloadFile();
 }

 void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
 {
    double bytesIn = double.Parse(e.BytesReceived.ToString());
    double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
    double percentage = bytesIn / totalBytes * 100;
    //  Label1.Text = percentage.ToString();        
 }

 protected void Button1_Click(object sender, EventArgs e)
 {
    List<string> urls = new List<string>();
    urls.Add("http://abcd.com/1.xml");
    urls.Add("http://abcd.com/2.xml");
    downloadFile(urls);
  }
}