文件超过1.0GB时出现下载错误

本文关键字:下载 错误 0GB 文件 | 更新日期: 2023-09-27 18:26:19

你好,我正在尝试制作一个可以下载文件的程序。问题是,当它下载超过1GB的文件时,它会崩溃和中断。有没有一种方法可以让它下载更大的文件?这是我使用的代码

private void button1_Click(object sender, EventArgs e)
{
    WebClient web = new WebClient();
    string listbox = listBox1.SelectedItem.ToString();
    web.DownloadFileAsync(new Uri(http://example.com/file.avi), location" + "file.avi");
    web.DownloadProgressChanged += new DownloadProgressChangedEventHandler(web_DownloadProgressChanged);
    web.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
}
private void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
    // Place for a message when the downloading has compleated
}             
void web_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
    int bytesin = int.Parse(e.BytesReceived.ToString());
    int totalbytes = int.Parse(e.TotalBytesToReceive.ToString());
    int kb1 = bytesin / 1024;
    int kb2 = totalbytes / 1024;
    toolStripStatusLabel1.Text = kb1.ToString() + "KB out of " + kb2.ToString() + "KB (" + e.ProgressPercentage.ToString() + "%)";
    progressBar1.Value = e.ProgressPercentage;             
}

文件超过1.0GB时出现下载错误

void web_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
    int bytesin = int.Parse(e.BytesReceived.ToString());
    int totalbytes = int.Parse(e.TotalBytesToReceive.ToString());
    int kb1 = bytesin / 1024;
    int kb2 = totalbytes / 1024;
    toolStripStatusLabel1.Text = kb1.ToString() + "KB out of " + kb2.ToString() + "KB (" + e.ProgressPercentage.ToString() + "%)";
    progressBar1.Value = e.ProgressPercentage;             
}

导致了您的问题。当BytesReceived或TotalBytesToReceive超过int32.MaxValue时,您正在将long转换为int,并得到OverflowException。

将方法更改为类似以下内容:

void web_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
    long kb1 = e.BytesReceived / 1024;
    long kb2 = e.TotalBytesToReceive / 1024;
    toolStripStatusLabel1.Text = kb1.ToString() + "KB out of " + kb2.ToString() + "KB (" + e.ProgressPercentage.ToString() + "%)";
    progressBar1.Value = e.ProgressPercentage;             
}