Need to convert longs web url's to short url's

Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #3429
    Nitesh
    Member

    Hello

    I have some long urls in my website and it some times create a problem while posting them on social site. Is there a way i can all the url’s to short urls (like tinyurl) within my webiste using c#

    #3440
    Pavan
    Member

    Hello Nitesh,
    This is very useful for posting our sites url on different sites and on forums because they restrict that site url with in specific length.
    Below is the code:

    public static string MakeTinyUrl(string Url)
        {
            //pass an url into this function and get the created tinyurl value as output
    
            try
            {
                string Result = Url;
    
                //only process if > 26 else keep same url
                //reason being tinyurl produces 26 char lengths 
                //so no point if url already <= 26
    
                if (Url.Length > 26)
                {
                    if (!Url.ToLower().StartsWith("http") && !Url.ToLower().StartsWith("ftp"))
                    {
                        Url = "http://" + Url;
                    }
                    System.Net.WebRequest request = System.Net.HttpWebRequest.Create("http://tinyurl.com/api-create.php?url=" + Url);
                    System.Net.WebResponse res = request.GetResponse();
    
                    using (System.IO.StreamReader reader = new System.IO.StreamReader(res.GetResponseStream()))
                    {
                        Result = reader.ReadToEnd();
                    }
    
                }
    
                return Result;
    
    
            }
            catch (Exception ex)
            {
                //if any exception just return the original Url seeing this is still valid as an url
                return Url;
            }
        }
    

    I am using in this example a Textbox and button you just type url in Textbox and press submit button then it will display a tiny url just above the Textbox . Simple copy the url and open in web browser.
    Like i am using Url:
    http://www.authorcode.com/your-first-facebook-windows-application-in-c/

    Result Tiny Url:
    http://tinyurl.com/6oouhqd

    
    
        protected void Button1_Click1(object sender, EventArgs e)
        {
            string Result = MakeTinyUrl(txt_url.Text);
               
            Response.Write(Result);
        }
    
    
    #3441

    good explanation….

Viewing 3 posts - 1 through 3 (of 3 total)
  • You must be logged in to reply to this topic.