The first function parse a string parameter to find urls and convert them into TinyURL with the second function:
public static string ToTinyURLs(string txt)
{
Regex regx = new Regex("http://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?", RegexOptions.IgnoreCase);
MatchCollection mactches = regx.Matches(txt);
foreach (Match match in mactches)
txt = txt.Replace(match.Value, GetTinyUrl(match.Value));
return txt;
}The second function call TinyURL service and return the response:
public static string GetTinyUrl(string Url)
{
try
{
if (Url.Length <= 12)
return Url;
if (!Url.ToLower().StartsWith("http") && !Url.ToLower().StartsWith("ftp"))
Url = "http://" + Url;
WebResponse webResponse = WebRequest.Create("http://tinyurl.com/api-create.php?url=" + Url).GetResponse();
using (StreamReader reader = new StreamReader(webResponse.GetResponseStream()))
return reader.ReadToEnd();
}
catch
{
return Url;
}
}