Click here to Skip to main content
15,949,686 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hey! I'm trying to make a download system with the progress, but when it goes to download, it shows that "downloaded" but in fact it ends up not downloading the file as it really should, the file is 0 bytes and in the progress it shows ( Ex: 18374Bytes / -1Bytes). I wanted to know how I can fix this.

What I have tried:

public static void DownloadFile()
{
WebClient client = new WebClient();
Uri uri = new Uri("https://drive.google.com/file/d/1Qfk1MsWuSFs1dfYVqISmIROCGA-Rcciy/view?usp=drivesdk");

client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgress);
client.DownloadFileAsync(uri, "test.apk");
}

private static void DownloadProgress(object sender, DownloadProgressChangedEventArgs e)
{
if (e.ProgressPercentage == 100)
{
Console.WriteLine("Downloaded {0}Bytes / {1}Bytes.", e.BytesReceived, e.TotalBytesToReceive);
//Console.WriteLine($"{e.BytesReceived / 1024 / 1024 }MB / {e.TotalBytesToReceive / 1024 / 1024 }MB");
}
else
{
Console.WriteLine("Downloaded {0}Bytes / {1}Bytes. {2}%", e.BytesReceived, e.TotalBytesToReceive);
//Console.WriteLine($"{e.BytesReceived / 1024 / 1024 }MB / {e.TotalBytesToReceive / 1024 / 1024 }MB");
Console.Clear();
}
}
}
Posted
Updated 4-Apr-22 0:27am
Comments
Richard MacCutchan 2-Apr-22 4:49am    
The -1 value suggest that the download has failed for some reason*. You need to check exactly what is being passed from the Google site.

*the URI you are using does not look like a complete filename, are you sure it is correct?
xuaugameplays 3-Apr-22 8:11am    
Ill check, thx dear :)

1 solution

WebClient.DownloadFileAsync[^] does not block the calling thread. Your method returns before the download has finished. It's likely that the WebClient instance will be destroyed when the method returns, so the download will be aborted.

Either use the DownloadFile method[^], which does block the calling thread; or make your method async and use the DownloadFileTaskAsync method[^]:
C#
public static async Task DownloadFile()
{
    using WebClient client = new WebClient();
    Uri uri = new Uri("...");
    client.DownloadProgressChanged += DownloadProgress;
    await client.DownloadFileTaskAsync(uri, "test.apk");
}
 
Share this answer
 
Comments
xuaugameplays 4-Apr-22 7:17am    
Thx, dude

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900