C # Download file from url

Can someone tell me how I can upload a file in my C # program from this URL: http://www.cryptopro.ru/products/cades/plugin/get_2_0

I am trying to use WebClient.DownloadFile, but I only get the html page instead of the file.

+4
source share
5 answers

Looking at Fiddler, the request fails if there is no legal U / A string, therefore:

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");
+10
source

I believe that would do the trick.

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

, , :

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");

- :

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

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

WebClient.DownloadData

byte[], , .

0

Sometimes the server does not allow downloading files with scripts / code. To take care of this, you need to configure the user agent header to trick the server that the request comes from the 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 the file.

0
source

Source: https://habr.com/ru/post/1608492/


All Articles