简体   繁体   中英

Link my Application with web site Use C#

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.

您可以使用HTML Agility Pack查找<img>标签。

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM