WebClient 403 Forbidden
I had this problem trying to download an image from a SharePoint site url. In my case setting the user-agent
to Other or blank in the header wasn't enough, I had to set the user-agent
as follows instead:
client.Headers.Add("user-agent", " Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0");
That solution came from this answer.
Just add a simple line before you make your download:
string url = ...
string fileName = ...
WebClient wb = new WebClient();
wb.Headers.Add("User-Agent: Other"); //that is the simple line!
wb.DownloadFile(url, fileName);
That's it.
403 may also be caused by TLS issues. To verify, you should check the text of the WebException.Response object.
catch (WebException ex)
{
if (ex.Response != null)
{
var response = ex.Response;
var dataStream = response.GetResponseStream();
var reader = new StreamReader(dataStream);
var details = reader.ReadToEnd();
}
}
If it is TLS then try adding this to your code to force TLS1.2.
For .net4:
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
For .net4.5 or later:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
You need to set appropriate http headers before calling your DownloadFile
method.
WebClient webClient = new WebClient();
webClient.Headers.Add("???", "???");
webClient.Headers.Add("???", "???");
webClient.Headers.Add("???", "???");
webClient.DownloadFile(address, filename);
To put correct values instead of these question marks might be tricky. You will need to download Fiddler or some other program or webbrowser extension to reveal what http headers are being sent to Google by your webbrowser and basically replicate the same request in your program.