How to Download a File from a Url in C#

How to download a file from a URL using c#

Lasse Vågsæther Karlsen is correct. Your browser is smart enough to decompress the file because the response contains the header:

content-encoding:"gzip"

You can download and decompress the file with this code (adjust accordingly for your file name, path, etc.)

void Main()
{
using (var client = new WebClient())
{
client.Headers.Add("accept", "*/*");
byte[] filedata = client.DownloadData("http://members.tsetmc.com/tsev2/excel/MarketWatchPlus.aspx?d=1396-08-08");

using (MemoryStream ms = new MemoryStream(filedata))
{
using (FileStream decompressedFileStream = File.Create("c:\\deleteme\\test.xlsx"))
{
using (GZipStream decompressionStream = new GZipStream(ms, CompressionMode.Decompress))
{
decompressionStream.CopyTo(decompressedFileStream);
}
}
}
}
}

C# Download file from URL

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

Download a file from website, without specific file url

Try this approach:

var client = new HttpClient
{
BaseAddress = new Uri("https://thunderstore.io/")
};

var response = await client.GetStreamAsync("package/download/Raus/IonUtility/1.0.1/");

var fn = Path.GetTempFileName();

using (var file = File.OpenWrite(fn))
{
await response.CopyToAsync(file);
}

At the end fn will hold the local file name. There is no dialog and you have the full control.



Related Topics



Leave a reply



Submit