Article

Convert URL to Shorten URL or Tiny URL in Asp.Net with C#

27 Jan 2018 Kamal Pratap
0 Comments 1873 Views
C#



Need to create the Tiny URL in Asp.Net C# then we will follow the code describe below. In this article we will consume the Tiny URL API in c# to get Tiny URL.

 

In my previous article How to convert URL to Shorten URL or Tiny URL in SQL Server we explain how to create the Tiny URL in SQL Server. 

On page load we pass the URL to the method to create Tiny URL.

        protected void Page_Load(object sender, EventArgs e)
        {
            string TinyURL = ToTinyURLS("http://www.freshcodehub.com");
            Response.Write(TinyURL);
        }

Check the given URL is valid, whether the URL is valid we will pass tthe URL into method to create the Tiny URL. We calling the Tiny URL API to create a shorten URL.

        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;
            }
        }

Once the code is successfully debug i will return the Tiny URL likes as given below

Output :- http://tinyurl.com/yaakqa74

Kamal Pratap

I have 6+ years experience in .Net technologies like Asp.Net, C#, WCF, Web Services, SQL Server, Ajax, LinQ. Currently I am working in Netcarrots Loyalty Services as a Software Developer.

Comments

No coments found to display!

Leave a Comment