How can I view images from a website in my application using language C#.
开发者_运维知识库I don't want to download all the page, I just want view the pictures in my application.
You can use the HTML Agility Pack to find <img>
tags.
You will need to download the html for the page using WebRequest class in System.Net.
You can then parse the HTML (using HTML Agility Pack) extract the URLs for the images and download the images, again using the WebRequest class.
Here is some sample code to get you started:
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;
}
You can use this code to download the raw bytes for a given URL (either the web page or the images themselves).
/// 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;
}
精彩评论