views:

589

answers:

4

I found the following code to create a tinyurl.com url:

http://tinyurl.com/api-create.php?url=http://myurl.com

This will automatically create a tinyurl url. Is there a way to do this using code, specifically C# in ASP.NET?

+2  A: 

You have to call that URL from your code, then read back the output from the server and process it.

Have a look at the System.Net.WebClient class, DownloadString (or better: DownloadStringAsync) seems to be what you want.

Michael Stum
+4  A: 

After doing some more research ... I stumbled upon the following code:

    public static string MakeTinyUrl(string url)
    {
        try
        {
            if (url.Length <= 30)
            {
                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;
        }
    }

Looks like it may do the trick.

mattruma
+2  A: 

Keep in mind if you're doing a full-scale app, that you're wiring in a pretty specific dependency to TinyURL's URL/API scheme. Maybe they have guarantees about their URL not changing, but it's worth checking out

Paul Betts
Thanks Paul ... good advice!
mattruma
+2  A: 

You should probably add some error checking, etc, but this is probably the easiest way to do it:

System.Net.Uri address = new System.Net.Uri("http://tinyurl.com/api-create.php?url=" + YOUR ADDRESS GOES HERE);
System.Net.WebClient client = new System.Net.WebClient();
string tinyUrl = client.DownloadString(address);
Console.WriteLine(tinyUrl);
mcrumley