In my case WebClient's DownloadData/DownloadFile/DownloadString methods showed different results than when downloading the file from a browser, like Chrome. First I thought it was an encoding problem and looped through all the encodings from Encoding.GetEncodings()
, but the output data showed nonsense characters. Then after much searching I ended up here.
I looked at the Response headers
in the Chrome browser Network tab as @han058 suggested and it read:
Cache-Control: public, max-age=900
content-disposition: attachment;filename=FILENAME.csv
Content-Encoding: gzip
Content-Length: 29310
Content-Type: text/plain; charset=utf-8
Date: Sat, 04 Jan 2020 20:20:13 GMT
Expires: Sat, 04 Jan 2020 20:35:14 GMT
Last-Modified: Sat, 04 Jan 2020 20:20:14 GMT
Server: Microsoft-IIS/10.0
Vary: *
X-Powered-By: ASP.NET
X-Powered-By: ARR/3.0
X-Powered-By: ASP.NET
So the response was encoded Content-Encoding: gzip
. In other words, I had to unzip the file, before I could read it.
using System;
using System.IO;
using System.IO.Compression;
using System.Net;
public class Program
{
static void Main(string[] args)
{
var url = new Uri("http://www.url.com/FILENAME.csv");
var path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
var fileName = "File.csv";
using (WebClient wc = new WebClient())
using (Stream s = File.Create(Path.Combine(path, fileName)))
using (GZipStream gs = new GZipStream(wc.OpenRead(url), CompressionMode.Decompress))
{
//Saves to C:\Users\[YourUser]\Desktop\File.csv
gs.CopyTo(s);
}
}
}