C# Download file from URL

2020-06-17 07:13发布

问题:

Can anybody tell me how i can download file in my C# program from that URL: http://www.cryptopro.ru/products/cades/plugin/get_2_0

I try to use WebClient.DownloadFile, but i'm getting only html page instead of file.

回答1:

Looking in Fiddler the request fails if there is not a legitimate U/A string, so:

WebClient wb = new WebClient();
wb.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.33 Safari/537.36");
wb.DownloadFile("http://www.cryptopro.ru/products/cades/plugin/get_2_0/cadeplugin.exe", "c:\\xxx\\xxx.exe");


回答2:

I belive this would do the trick.

WebClient wb = new WebClient();
wb.DownloadFile("http://www.cryptopro.ru/products/cades/plugin/get_2_0/cadeplugin.exe","file.exe");


回答3:

If you need to know the download status or use credentials in order to make the request, I'll suggest this solution:

WebClient client = new WebClient();
Uri ur = new Uri("http://remoteserver.do/images/img.jpg");
client.Credentials = new NetworkCredential("username", "password");
client.DownloadProgressChanged += WebClientDownloadProgressChanged;
client.DownloadDataCompleted += WebClientDownloadCompleted;
client.DownloadFileAsync(ur, @"C:\path\newImage.jpg");

And her it is the implementation of the callbacks:

void WebClientDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
    Console.WriteLine("Download status: {0}%.", e.ProgressPercentage);
}

void WebClientDownloadCompleted(object sender, DownloadDataCompletedEventArgs e)
{
    Console.WriteLine("Download finished!");
}


回答4:

Try WebClient.DownloadData

You would get response in the form of byte[] then you can do whatever you want with that.



回答5:

Sometimes a server would not let you download files with scripts/code. to take care of this you need to set user agent header to fool the server that the request is coming from browser. using the following code, it works. Tested ok

 var webClient=new WebClient();
 webClient.Headers["User-Agent"] =
                "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36";
 webClient.DownloadFile("the url","path to downloaded file");

this will work as you expect, and you can download file.



标签: c# file download