I am currently working on a small project using ASP.Net MVC and I want to incorporate a TinyUrl facility such as that of www.tinyurl.com and the million other clones there are. I found this awesome piece of code that does the trick beautifully! I found the code @ http://blogs.msdn.com/bramveen/archive/2009/01/06/converting-url-to-tinyurl-in-c.aspx
It was really quick to implement and works really nicely.
protected 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) { string tURL = MakeTinyUrl(match.Value); txt = txt.Replace(match.Value, tURL); } return txt; } public static string MakeTinyUrl(string Url) { try { if (Url.Length <= 12) { return Url; } if (!Url.ToLower().StartsWith("http") && !Url.ToLower().StartsWith("ftp")) { Url = "http://" + Url; } var request = WebRequest.Create("http://tinyurl.com/api-create.php?url=" + Url); var res = request.GetResponse(); string text; using (var reader = new StreamReader(res.GetResponseStream())) { text = reader.ReadToEnd(); } return text; } catch (Exception) { return Url; } }
Hope this can as useful to you as it was for me!
