我正在编写非常简单的应用程序。它应该是从互联网上下载文件。我有要保存在表中的文件的URL和名称。但是我的代码不能工作。
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;
}示例url:http://books.google.pl/books?id=yOz1ePt39WQC&pg=PA2&img=1&zoom=3&hl=pl&sig=ACfU3U0MDQtXGU_3YVqGvcsDiWLLcKh0KA&w=800&gbd=1
示例名称:002.png
文件将保存为PNG图像,但我得到的是以<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">开头的文件
第二个问题。如何在尝试下载时检测HTTP 404错误?
编辑:我的错。我的链接不正确。用&替换&后,它们是正确的。示例链接(已更正):
http://books.google.pl/books?id=yOz1ePt39WQC&pg=PA2&img=1&zoom=3&hl=pl&sig=ACfU3U0MDQtXGU_3YVqGvcsDiWLLcKh0KA&w=800&gbd=1
尽管如此,我仍然不能正确下载PNG。它们不会打开的。但至少它们不是HTML页面。我在想,尝试将它们保存为字符串不是一个好主意。但我不知道我还能怎么做。也许使用byte[]或其他什么?
发布于 2011-04-28 20:29:10
你试过WebClient.DownloadFile吗?
string url = "http://books.google.pl/books?id=yOz1ePt39WQC&pg=PA2&img=1&zoom=3&hl=pl&sig=ACfU3U0MDQtXGU_3YVqGvcsDiWLLcKh0KA&w=800&gbd=1";
string file = "002.png";
WebClient wc = new WebClient();
wc.DownloadFile(url, file);将在应用程序目录中将图像保存为002.png。
https://stackoverflow.com/questions/5817285
复制相似问题