How to download file asynchronously from webserver in

In this post I am going to show how to download file asynchronously from server using
  •  Open Visual Studio and create a new WebApplication or WebSite
  •  Open Default.aspx page and paste following code

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default"
    Async="true" %>

<html xmlns="">
<head id="Head1" runat="server">
    <script src=""></script>
    <script type="text/javascript">
        function WaitProgress() {
            $("#Indicator").text("please wait...");
        function FinishProgress(contentState) {
    <form id="form1" runat="server">
    <asp:Button ID="btnDownload" runat="server" Text="DownLoadData" OnClientClick="WaitProgress();"
        OnClick="btnDownload_Click" />
    <p id="Indicator">

  • Open Default.aspx.cs file and pate following code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
using System.Net;

public partial class _Default : System.Web.UI.Page
    private const string FILE_PATH = @"C:\Temp\test.pdf";
    protected void btnDownload_Click(object sender, EventArgs e)
    private void DownLoadFile()
        //define the url
        string url = "";
        //define the local path
        string filepath = FILE_PATH;
        Uri uri = new Uri(url);
        WebClient client = new WebClient();
        client.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(client_DownloadFileCompleted);
        client.Credentials = new NetworkCredential();
        client.DownloadFileAsync(uri, filepath);

    void client_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        string contentState = "File Downloaded Successfully!!!";
        if (e.Error != null)
            contentState = e.Error.Message;
            object userstate = e.UserState;
            this.ClientScript.RegisterStartupScript(this.GetType(), "finishDownload", "FinishProgress('" + contentState + "');", true);


No comments:

Post a Comment