using System; using System.Text.RegularExpressions; using System.Net;
using System.Web; using System.Text;
public static class Program
public static string RemoveUnicodeControlChars(this string s) {
StringBuilder sb = new StringBuilder(s.Length);
for (int i = 0; i < s.Length; i++)
if ( !Char.IsControl(s[i]) )
public static string URLExpander(this string URL) {
string urlText = URL.RemoveUnicodeControlChars();
if (string.IsNullOrWhiteSpace(urlText))
bool result = Uri.TryCreate(urlText, UriKind.Absolute, out uriResult)
&& (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps
|| uriResult.Scheme == Uri.UriSchemeFtp || uriResult.Scheme == Uri.UriSchemeFile
HttpWebRequest req = null;
HttpWebResponse response;
req = (HttpWebRequest)WebRequest.Create(uriResult);
req.AllowAutoRedirect = false;
catch (NotSupportedException)
catch (ArgumentNullException)
catch (System.Security.SecurityException)
catch (UriFormatException)
string redirectedURL = "";
response = (HttpWebResponse)req.GetResponse();
if ((int)response.StatusCode >= 300 && ((int)response.StatusCode < 400))
redirectedURL = response.Headers[HttpResponseHeader.Location];
else if ((int)response.StatusCode < 300 || (int)response.StatusCode >= 400)
redirectedURL = uriResult.ToString();
catch (System.Net.WebException)
catch (System.Net.ProtocolViolationException)
catch (InvalidOperationException)
catch (NotSupportedException)
redirectedURL = HttpUtility.UrlDecode(redirectedURL);
public static void Main()
string testURL = "http://bit.ly/AzureAITranslation";
string testURL2 = "https://metadataconsulting.blogspot.com";
string expandoURL = testURL.URLExpander();
if (testURL == expandoURL)
Console.WriteLine("source URL same as output URL");
else if (testURL + "/" == expandoURL)
Console.WriteLine("source URL same as output URL");
Console.WriteLine("source URL expands to new URL");
Console.WriteLine(testURL + "\nexpands to\n" + testURL.URLExpander());
expandoURL = testURL2.URLExpander();
if (testURL2 == expandoURL)
Console.WriteLine("source URL same as output URL");
else if (testURL2 + "/" == expandoURL)
Console.WriteLine("source URL same as output URL");
Console.WriteLine("source URL expands to new URL");
Console.WriteLine(testURL2 + "\nexpands to\n" + testURL2.URLExpander());