Saturday, December 29, 2007

C#: CheckUrl class for checking contents of an URL

using System;
using System.Text;
using System.IO;
using System.Net;

namespace CheckUrl
{
public class CheckUrl
{
public string GetUrlResponse(string url, string proxyAddress)
{
StringBuilder sb = new StringBuilder();
byte[] buf = new byte[8192];
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
if (proxyAddress != null && proxyAddress.Length > 0)
{
System.Net.WebProxy proxy = new WebProxy(proxyAddress);
proxy.BypassProxyOnLocal = true;
proxy.Credentials = CredentialCache.DefaultCredentials;
request.Proxy = proxy;
}
request.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();
string tempString = null;
int count = 0;

do
{
count = resStream.Read(buf, 0, buf.Length);
if (count != 0)
{
tempString = Encoding.ASCII.GetString(buf, 0, count);
sb.Append(tempString);
}
}
while (count > 0);

return sb.ToString();
}

public bool CheckUrlForContentMatch(string url, string proxy, string content)
{
string response = getUrlResponse(url, proxy);

// Remove all carriage returns, starting & trailing spaces, tab characters and make lower cacse
response = response.Trim().Replace("\r", string.Empty).Replace("\n", string.Empty).Replace("\t",string.Empty).ToLower();
content = content.Trim().Replace("\r", string.Empty).Replace("\n", string.Empty).Replace("\t", string.Empty).ToLower();

int startPos = response.IndexOf(content);
if (startPos == -1)
return false;
else
return true;
}

}
}

No comments:

Post a Comment

Please use your common sense before making a comment, and I truly appreciate your constructive criticisms.