Convert Plain Text URL to Link

Last project I got a small but interesting issue in which I have to convert plain text url to html link and also check if url is in correct format then only I need to convert it to link otherwise as it is displayed in my webpage. I have create following C# function for doing that.

  1. private string ConvertTextUrlToLink(string url)  
  2. {  
  3.    string regex = @"((www\.|(http|https|ftp|news|file)+\:\/\/)[_.a-z0-9-]+\.
  4.    [a-z0-9\/_:@=.+?,##%&~-]*[^.|\'|\# |!|\(|?|,| |>|<|;|\)])";  
  5.    Regex r = new Regex(regex, RegexOptions.IgnoreCase);  
  6.    return r.Replace(url, "a href=\"$1\" title=\"Click here to open in a new window or tab\" 
  7.    target=\"_blank\">$1</a>").Replace("href=\"www""href=\"http://www");  
  8. }  
This function accept url in text format and by using regular expression it checks if that is correct url format or not if yes then it convert to HTML link otherwise return plain text.

In my aspx page I am creating a div like:
  1. <div id="UrlDiv" runat ="server" >  
  2. </div>  
After that passing url to above function in page load and text the result.

Case 1
  1. string Url = "www.google.com";  
  2.   
  3. UrlDiv.InnerHtml =ConvertTextUrlToLink(Url);  
Output

www.google.com // converted to link

Case 2
  1. string Url = "google.com";  
  2. UrlDiv.InnerHtml =ConvertTextUrlToLink(Url);  
Output

google.com // plain text


Above is small but very interesting code it may be useful for all.