I’m writing very simple application. It is supposed to download files from internet. I have URLs and names for files to save in tables. But my code doesn’t work.
for (int i = 1; i < links.Length; i++)
{
Uri uri = new Uri(links[i]);
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri);
webRequest.Method = "GET";
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
Stream responseStream = webResponse.GetResponseStream();
StreamReader responseStreamReader = new StreamReader(responseStream);
String result = responseStreamReader.ReadToEnd();
StreamWriter w = new StreamWriter(savepath + names[i]);
w.Write(result);
w.Close();
break;
}
example url:
http://books.google.pl/books?id=yOz1ePt39WQC&pg=PA2&img=1&zoom=3&hl=pl&sig=ACfU3U0MDQtXGU_3YVqGvcsDiWLLcKh0KA&w=800&gbd=1
example name:
002.png
Files are to be saved as PNG image but instead I get something that begins with
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
Second qestion. How can I detect HTTP 404 error when trying to download?
EDIT:
My bad. my links were incorrect. After replacing & with & they are correct.
Example link (correctted):
http://books.google.pl/books?id=yOz1ePt39WQC&pg=PA2&img=1&zoom=3&hl=pl&sig=ACfU3U0MDQtXGU_3YVqGvcsDiWLLcKh0KA&w=800&gbd=1
Despite of that I can’t still download PNGs correctly.
They are not opening. But at least they are not HTML pages.
I’m thinking that trying to save them as a string is not good idea. But I don’t know how else I could do that. Maybe using byte[] or something?
Have you tried WebClient.DownloadFile ?
will save the image in the application directory as 002.png.