Ben
Ben

Reputation: 43

Downloading Error With Files over 1.0GB

Hello I'm trying to make a program that can download a file problem is when it downloads a file that is over 1GB it Crashes and breaks is there a way to make it so it can download files that are way bigger Here is the code I'm using

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;             
}

Upvotes: 0

Views: 180

Answers (1)

Camilo Terevinto
Camilo Terevinto

Reputation: 32071

This

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;             
}

is causing your issue. You are converting a long to int and getting an OverflowException once BytesReceived or TotalBytesToReceive go above int32.MaxValue.

Change the method to something like this:

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;             
}

Upvotes: 1

Related Questions