2012-02-13 172 views
0

編輯我的代碼中使用Web客戶端......還是不工作保存HTML文件路徑

string hhtmlurl = /Thumbnail.aspx?productID=23&Firstname=jimmy&lastnight=smith; 

string strFileName = string.Format("{0}_{1}", hfUserID.Value, Request.QueryString["pid"].ToString() + documentID.ToString()); 
WebClient client = new WebClient(); 
client.DownloadFile("http://www.url.ca/" + hhtmlurl.Value + "card=1", strFileName); 
+0

它是如何工作的?它有什麼作用? – svick 2012-02-13 17:23:50

回答

0

嘗試此方法。這會給你整個html內容的字符串返回值。把這個字符串寫在你想要的任何文件中

public string GetHtmlPageContent(string url) 
    { 
     HttpWebResponse siteResponse = null; 
     HttpWebRequest siteRequest = null; 
     string content= string.Empty; 

     try 
     { 
      Uri uri = new Uri(url); 
      siteRequest = (HttpWebRequest)HttpWebRequest.Create(url); 
      siteResponse = (HttpWebResponse)siteRequest.GetResponse(); 

      content = GetResponseText(siteResponse); 
     } 
     catch (WebException we) 
     { 
      // Log error 
     } 
     catch (Exception e2) 
     { 
      // Log error 
     } 

     return content; 
    } 

     public string GetResponseText(HttpWebResponse response) 
    { 
     string responseText = string.Empty; 

     if (response == null) 
      return string.Empty; 

     try 
     { 
      StreamReader responseReader = new StreamReader(response.GetResponseStream()); 
      responseText = responseReader.ReadToEnd(); 
      responseReader.Close(); 
     } 
     catch (Exception ex) 
     { 
      // Log error 
     } 

     return responseText; 
    } 

希望這會對你有所幫助。

+0

在此代碼中,我是否保存該文件並將其存入我自己的文件名? – user979331 2012-02-13 15:10:46

+0

該部分在此處不可用,您必須執行該操作。 l我上面的方法,它會返回整個網頁內容的字符串。然後使用Streamwriter(http://msdn.microsoft.com/en-us/library/6ka1wd3w.aspx)將該字符串寫入另一個文件 – 2012-02-13 17:22:51

+0

Worked !!!了不起的傢伙! – user979331 2012-02-15 15:14:08

0

相反的FileStream的,使用WebClient類,它提供了簡單的興高采烈方法DownloadFile()

WebClient client = new WebClient(); 
client.Downloadfile("http://www.url.ca/" + hhtmlurl + "card=1", strFileName); 
+0

嗯...它似乎沒有工作....我已經注意到,我的client.Downloadfile是不是像你的綠色..黑色我使用System.net,我錯過了什麼? – user979331 2012-02-13 06:18:50

+0

請確保你的代碼中有'使用System.Net;'指令,或者顯式調用'System.Net.WebClient client = new System.Net.WebClient()' – 2012-02-13 06:24:11

+0

還沒有任何事情:(我在 – user979331 2012-02-13 06:33:32