将我的应用程序链接到网站使用C#

将我的应用程序链接到网站使用C#

问题描述:

如何在我的应用程序中使用C#语言查看网站中的图像。将我的应用程序链接到网站使用C#

我不想下载所有页面,我只想在我的应用程序中查看图片。

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

您需要使用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; 
} 

您可以使用此代码下载原始字节为某个网址(无论是网页或图像本身)。

+0

使用`WebClient`。 – SLaks 2011-02-18 00:18:24

+0

是的,这也是可能的http://stackoverflow.com/questions/1694388/webclient-vs-httpwebrequest-httpwebresponse – 2011-02-18 00:20:31

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