2010-11-26 84 views
0

我試圖加載使用C#中的HTML內容(模擬PHP函數 - 的file_get_contents)使用下面的代碼:C#Web客戶端:在HTML無法加載圖像時加載網頁

protected string file_get_contents(string fileName) 
{ 
    string sContents = string.Empty; 
    if (fileName.ToLower().IndexOf("http:") > -1) 
    { // URL 
    System.Net.WebClient wc = new System.Net.WebClient(); 
    byte[] response = wc.DownloadData(fileName); 
    sContents = System.Text.Encoding.ASCII.GetString(response); 
    } else { 
    // Regular Filename 
    System.IO.StreamReader sr = new System.IO.StreamReader(fileName); 
    sContents = sr.ReadToEnd(); 
    sr.Close(); 
    } 
return sContents; 
} 

然而,這不會在呈現內容時在html中加載圖像。但是,當使用PHP file_get_content時,它會在呈現內容時在HTML中加載圖像。

任何人有任何想法?

+1

你如何渲染內容,以及img標籤是什麼樣的?另外,你爲什麼使用DownloadData和Encoding.ASCII而不僅僅是DownloadString? – 2010-11-26 14:04:20

回答

0

查看file_get_contents的文檔,使用WebClient和此函數下載HTML頁面的內容應該沒有區別。 在這兩種情況下,你會得到一個字符串是這樣的:

string html = @"<!DOCTYPE html> 
<html> 
<head> 
    <title>Hello World</title> 
</head> 
<body> 
    Image: <img src=""/image/test.png""> 
</body> 
</html>"; 

當然,/image/test.png是相對於您下載的HTML頁面的URL。 因此,如果您從http://www.example.com/test.html下載HTML頁面並在http://www.yourdomain.net/foo/bar/qux.html上呈現檢索到的數據,則圖片標記將引用http://www.yourdomain.net/image/test.png而不是http://www.example.com/image/test.png

在呈現HTML頁面之前,您需要將相對URL重寫爲絕對URL。 查看此任務的Html Agility Pack