The site provides links as http://www.example.com/download.php?id=53979 . I know that this is a pdf file and want to download it via a C# program. Is this possible and if yes, how?
Asked
Active
Viewed 3,339 times
-3
-
1possible duplicate of [How to download a file from a URL in C#?](http://stackoverflow.com/questions/307688/how-to-download-a-file-from-a-url-in-c) – David Sep 29 '13 at 11:18
-
Yes this works when the link is like http://www.example.com/asd.pdf but not in this case. – baris_ercan Sep 29 '13 at 11:19
-
1The text of the URL doesn't make a difference. When you try to download the file, in what way does it "not work"? – David Sep 29 '13 at 11:21
-
It downloads an html file. – baris_ercan Sep 29 '13 at 11:24
-
Which means the server is serving the file incorrectly, or you have the wrong URL. All the client knows is what the server sends it. Do you have an example of this? – David Sep 29 '13 at 11:27
-
For example, when you go in http://www.datasheet4u.com/datasheet/L/M/7/LM741_NationalSemiconductor.pdf.html and click on the first link LM741, the browser downloads the file. But when you type directly http://www.datasheet4u.com/download.php?id=53979 into browser which is the same link, nothing gets downloaded. – baris_ercan Sep 29 '13 at 11:32
1 Answers
4
In order to download a file, you simply need to use the WebClient
object like in the question referenced above:
using (var client = new WebClient())
client.DownloadFile("http://www.datasheet4u.com/download.php?id=53979", "datasheet.pdf");
What makes your case slightly different has nothing to do with the server being written in PHP or anything like that. The link you provided (http://www.datasheet4u.com/datasheet/L/M/7/LM741_NationalSemiconductor.pdf.html) appears to be checking Referer
headers when serving the file. This is likely some attempt on their part to prevent what you're trying to do, but it doesn't actually prevent it.
All you need to do is add a Referer
header to the request. Something like this:
using (var client = new WebClient())
{
client.Headers.Add("Referer","http://www.datasheet4u.com/datasheet/L/M/7/LM741_NationalSemiconductor.pdf.html");
client.DownloadFile("http://www.datasheet4u.com/download.php?id=53979", "datasheet.pdf");
}
The method for downloading the file is still the same. The server just requires that you send an extra piece of information in the request.