winform 下载程序
时间: 2023-11-15 15:07:06 浏览: 36
您可以使用 C# 编写一个 WinForm 下载程序,以下是一个简单的示例:
```csharp
using System;
using System.ComponentModel;
using System.Windows.Forms;
using System.Net;
namespace DownloadManager
{
public partial class MainForm : Form
{
private WebClient webClient;
public MainForm()
{
InitializeComponent();
}
private void btnDownload_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(txtUrl.Text))
{
MessageBox.Show("请先输入下载链接!");
return;
}
if (webClient != null)
{
MessageBox.Show("当前已有下载任务!");
return;
}
webClient = new WebClient();
webClient.DownloadProgressChanged += WebClient_DownloadProgressChanged;
webClient.DownloadFileCompleted += WebClient_DownloadFileCompleted;
string fileName = txtUrl.Text.Substring(txtUrl.Text.LastIndexOf("/") + 1);
string savePath = AppDomain.CurrentDomain.BaseDirectory + fileName;
webClient.DownloadFileAsync(new Uri(txtUrl.Text), savePath);
}
private void WebClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
progressBar.Value = e.ProgressPercentage;
lblProgress.Text = $"{e.ProgressPercentage}% ({e.BytesReceived / 1024}KB/{e.TotalBytesToReceive / 1024}KB)";
}
private void WebClient_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
webClient.Dispose();
webClient = null;
if (e.Error != null)
{
MessageBox.Show($"下载出错:{e.Error.Message}");
return;
}
MessageBox.Show("下载完成!");
}
}
}
```