Converting url to tinyURL in C#

Hi All,

I’m using a lot of twitter lately and was looking for a nice twitter client in WPF which I found in Witty Twitter. The only feature that was missing was automatically converting a URL to tinyurl.

I downloaded the source of wittytwitter to see if it was easy to add this functionality.

It took me more time to donwloand and install TortoiseSVN than to add the feature.

Here is the code which can be used to parse any string for urls formatted as https://www.xyz.com

 protected string ToTinyURLS(string txt)
{
    Regex regx = new Regex("https://([\\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 = "https://" + Url;
        }
        var request = WebRequest.Create("https://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;
    }
}

Thanks to Faraz Shah Khan and Emad Ibrahim

I’ll be sending the update to the witty team ASAP.

Thanks

Bram