WinForm下载文件并显示下载进度示例



WinForm下载文件并显示下载进度示例

/// <summary>
/// 显示进度
/// </summary>
/// <param name="val"></param>
private void ProgressBar_Value(int val)
{
    progressBar1.Value = val;
    label1.Text = val.ToString() + "%";
}

/// <summary>
/// 下载文件
/// </summary>
/// <param name="url"></param>
/// <param name="savefile"></param>
/// <param name="downloadProgressChanged"></param>
/// <param name="downloadFileCompleted"></param>
private void DownloadFile(string url, string savefile, Action<int> downloadProgressChanged, Action downloadFileCompleted)
{
    WebClient client = new WebClient();
    if (downloadProgressChanged != null)
    {
        client.DownloadProgressChanged += delegate(object sender, DownloadProgressChangedEventArgs e)
        {
            this.Invoke(downloadProgressChanged, e.ProgressPercentage);
        };
    }
    if (downloadFileCompleted != null)
    {
        client.DownloadFileCompleted += delegate(object sender, AsyncCompletedEventArgs e)
        {
            this.Invoke(downloadFileCompleted);
        };
    }
    client.DownloadFileAsync(new Uri(url), savefile);
}
delegate void Action(); //.NET Framework 2.0得自定义委托Action

/// <summary>
/// 点击下载
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
    DownloadFile("http://www.mzwu.com/update.zip", @"F:\update.zip", ProgressBar_Value, null);
}

参考资料

[1].How to download a file in C#:http://www.fluxbytes.com/csharp/how-to-download-a-file-in-c-progressbar-and-download-speed/
[2].Download File Asynchronously With ProgressBar:http://www.dreamincode.net/forums/topic/115491-download-file-asynchronously-with-progressbar/
[3].Asynchronous File Download with Progress Bar:http://stackoverflow.com/questions/9459225/asynchronous-file-download-with-progress-bar

评论: 0 | 引用: 0 | 查看次数: 3196
发表评论
登录后再发表评论!