CSDownloadURL : Download Contents of a Web Page


CSDownloadURL is a class which has two functions - SetURL and DownloadURL. The set URL sets the current URL and GetDownload downloads the URL contents and returns its contents in a string.

Note: This class was written in Beta 1. In recent .NET versions, the WebRequestFactory class is no longer valid. This is now updated to RC3.

You can use the WebRequest class to download the contents of a web page. The WebRequest uses HTTP protocol to download the contents. You use Create method of WebRequest to create a WebRequest object by passing a URL as a parameter. After that you can call GetResponse and GetResponseStream methods. The GetResponseStream method returns data in a Stream object.

namespace Project5
{
using System;
using System.Text;
using System.IO;
using System.Net;
/// <summary>
/// Summary description for Class1.
/// </summary>
public class CSDownloadURL
{
private string m_strURL;
public void setURL1( string strURL )
{
m_strURL = strURL;
}
public void DownloadURL(out string strContents)
{
WebRequest req = WebRequest.Create(m_strURL);
WebResponse res = req.GetResponse();
int iTotalBuff = 0;
Byte[] Buffer =
new Byte[128];
Stream stream = res.GetResponseStream();
iTotalBuff = stream.Read(Buffer, 0, 128);
StringBuilder strRes =
new StringBuilder("");
while(iTotalBuff != 0)
{
strRes.Append(Encoding.ASCII.GetString(Buffer, 0, iTotalBuff));
iTotalBuff = stream.Read(Buffer, 0, 128);
}
strContents = strRes.ToString();
}
}

Use the CSDownloadURL

class TestUrl
{
public static void Main()
{
string strOut;
CSDownloadURL web = new CSDownloadURL();
web.setURL1("
http://www.mindcracker.com");
web.DownloadURL( out strOut);
Console.WriteLine(strOut);
}
}

Up Next
    Ebook Download
    View all
    Learn
    View all