views:

119

answers:

4

given a url how can i download the webpage to my harddrive with asp.net

e.g. if you open the url http://www.cnn.com in ie6 and use file save as, it will download the html page to your system.

how can i achieve this by asp.net

A: 

Use 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();
womp
You really should be using using. :)
ChaosPandion
+1  A: 

This should do the job. But you will need to consider security if you are doing it from within an ASP.NET page.

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();
     }
David McEwing
A: 
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());
}
ChaosPandion
here i have only html, i am looking for a htm folder where it will have all the images of the url
vamsivanka
+2  A: 

As womp said, using WebClient is simpler in my opinion. Here is my simpler example :

string result;
using (WebClient client = new WebClient()) {
    result = client.DownloadString(address);
}
// Just save the result to a file or do what you want..
Canavar
I knew they had to already have done this! +1
ChaosPandion
I can able to do this, which downloads source code of that page. Using client As New WebClient() client.DownloadFile("http://www.cnn.com", "c:\test.html") End Usingbut what i am missing in this are the image downloads. from the above i am getting only the image location not the real images itself.
vamsivanka