将我的应用程序链接到网站使用C#
答
您需要使用System.Net中的WebRequest类下载页面的html。
然后,您可以解析HTML(使用HTML Agility Pack),然后使用WebRequest类提取图像的URL并下载图像。
下面是一些示例代码,您开始:
static public byte[] GetBytesFromUrl(string url)
{
byte[] b;
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
WebResponse myResp = myReq.GetResponse();
Stream stream = myResp.GetResponseStream();
using (BinaryReader br = new BinaryReader(stream))
{
b = br.ReadBytes(100000000);
br.Close();
}
myResp.Close();
return b;
}
您可以使用此代码下载原始字节为某个网址(无论是网页或图像本身)。
答
/// Returns the content of a given web adress as string.
/// </summary>
/// <param name="Url">URL of the webpage</param>
/// <returns>Website content</returns>
public string DownloadWebPage(string Url)
{
// Open a connection
HttpWebRequest WebRequestObject = (HttpWebRequest)HttpWebRequest.Create(Url);
// You can also specify additional header values like
// the user agent or the referer:
WebRequestObject.UserAgent = ".NET Framework/2.0";
WebRequestObject.Referer = "http://www.example.com/";
// Request response:
WebResponse Response = WebRequestObject.GetResponse();
// Open data stream:
Stream WebStream = Response.GetResponseStream();
// Create reader object:
StreamReader Reader = new StreamReader(WebStream);
// Read the entire stream content:
string PageContent = Reader.ReadToEnd();
// Cleanup
Reader.Close();
WebStream.Close();
Response.Close();
return PageContent;
}
使用`WebClient`。 – SLaks 2011-02-18 00:18:24
是的,这也是可能的http://stackoverflow.com/questions/1694388/webclient-vs-httpwebrequest-httpwebresponse – 2011-02-18 00:20:31