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
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
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();
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();
}
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());
}
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..