2009-09-03 68 views
0

给出了一个网址我如何使用asp.net将网页下载到我的硬盘上通过asp.net下载网页

如果您在ie6中打开url http://www.cnn.com并使用文件另存为,它会将html页面下载到您的系统。

我如何通过asp.net

+0

只是HTML或HTML和图像? – 2009-09-03 04:23:55

回答

0

使用System.Net.WebClient实现这一目标。

WebClient client = new WebClient(); 

Stream data = client.OpenRead ("http://www.myurl.com"); 
StreamReader reader = new StreamReader(data); 
string s = reader.ReadToEnd(); 
Console.WriteLine (s); 
data.Close(); 
reader.Close(); 
+3

你真的应该使用使用。 :) – ChaosPandion 2009-09-03 04:27:23

1

这应该做的工作。但是如果您是在ASP.NET页面中执行此操作,则需要考虑安全性。

public static void GetFromHttp(string URL, string FileName) 
     { 
      HttpWebRequest HttpWReq = CreateWebRequest(URL); 

      HttpWebResponse HttpWResp = (HttpWebResponse)HttpWReq.GetResponse(); 
      Stream readStream = HttpWResp.GetResponseStream(); 
      Byte[] read = new Byte[256]; 

      Stream fs = new FileStream(FileName, FileMode.Create, FileAccess.Write); 

      int count = readStream.Read(read, 0 , 256); 
      while (count > 0) 
      { 
       fs.Write(read, 0, count); 
       count = readStream.Read(read, 0, 256); 
      } 
      readStream.Close(); 

      HttpWResp.Close(); 
      fs.Flush(); 
      fs.Close(); 
     } 
0
String url = "http://www.cnn.com"; 
var hwr = (HttpWebRequest)HttpWebRequest.Create(url); 
using (var r = hwr.GetResponse()) 
using (var s = new StreamReader(r.GetResponseStream())) 
{ 
    Console.Write(s.ReadToEnd()); 
} 
+0

这里我只有html,我正在寻找一个htm文件夹,它将有所有的url的图像 – vamsivanka 2009-09-08 02:19:00

2

正如womp说,使用Web客户端在我看来简单。这里是我更简单的例子:

string result; 
using (WebClient client = new WebClient()) { 
    result = client.DownloadString(address); 
} 
// Just save the result to a file or do what you want.. 
+0

我知道他们必须已经做到了这一点! +1 – ChaosPandion 2009-09-03 05:37:31

+0

我可以做到这一点,下载该页面的源代码。 使用客户端作为新的WebClient() client.DownloadFile(“http://www.cnn.com”,“c:\ test.html”) 结束使用 但我缺少的是图像下载。从上面我得到的只是图像的位置而不是真实的图像本身。 – vamsivanka 2009-09-08 02:17:31