0

给定一个网址,我如何使用 asp.net 将网页下载到我的硬盘

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

我怎样才能通过asp.net实现这一点

4

4 回答 4

3

正如womp所说,在我看来,使用 WebClient 更简单。这是我更简单的例子:

string result;
using (WebClient client = new WebClient()) {
    result = client.DownloadString(address);
}
// Just save the result to a file or do what you want..
于 2009-09-03T05:35:23.283 回答
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();
        }
于 2009-09-03T04:22:38.627 回答
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();
于 2009-09-03T04:21:43.637 回答
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());
}
于 2009-09-03T04:26:37.480 回答