If you make sure that you only have the domain names (and arguably ips) in the list Bannedsites then you can look for the domain only.
To get the domain of a Uri, do as follows:
var uri = new Uri("http://stackoverflow.com/questions/11060418/c-sharp-string-parsing-containing-in-a-list");
Console.WriteLine(uri.DnsSafeHost);
The output is:
stackoverflow.com
Now you can get it to work like this (remember to store in upper case in Bannedsites):
var uri = new Uri(input)
if(Bannedsites.Contains(uri.DnsSafeHost.ToUpper(CultureInfo.InvariantCulture)))
{
//Don't go to that site
}
else
{
//Go to that site
}
This will also ensure that the domain didn't appear as a part of another string by chance, for example as part of a parameter.
Also note that this method will give you subdomains, so:
var uri = new Uri("http://msdn.microsoft.com/en-US/");
Console.WriteLine(uri.DnsSafeHost);
returns:
msdn.microsoft.com
and not only:
microsoft.com
You may also verify that the uri is valid with uri.IsWellFormedOriginalString():
var uri = new Uri(input)
if(uri.IsWellFormedOriginalString() && Bannedsites.Contains(uri.DnsSafeHost))
{
//Don't go to that site
}
else
{
//Go to that site
}
Now, let's say that you want to take into account the detail of subdomains, well, you can do this:
var uri = new Uri(input)
if(uri.IsWellFormedOriginalString() && Bannedsites.Any(x => uri.DnsSafeHost.EndsWith(x))
{
// Don't go to that site
}
else
{
// Go to that site
}
Lastly if you are banning particular pages not whole webs (in which case caring for the subdomains makes no sense), then you can do as follows:
var uri = new Uri(input)
if(uri.IsWellFormedOriginalString() && Bannedsites.Contains((uri.DnsSafeHost + uri.AbsolutePath)))
{
//Don't go to that site
}
else
{
//Go to that site
}
Using AbsolutePath you take care of those "?" and "#" often used to pass parameters, and any other character that doesn't change the requested page.
You may also consider using Uri.Compare and store a list of Uri instead of a list of strings.
I leave you the task of making the comparisons case invariant as RFC 1035 says:
"
For all parts of the DNS that are part of the official protocol, all
comparisons between character strings (e.g., labels, domain names, etc.)
are done in a case-insensitive manner.
"