static string EscapeUserName (string userName)
{
StringBuilder escaped;
int startIndex, index;
if ((index = userName.IndexOfAny (ReservedUriCharacters)) == -1)
return userName;
escaped = new StringBuilder ();
startIndex = 0;
do {
escaped.Append (userName, startIndex, index - startIndex);
escaped.Append (HexEscape (userName[index++]));
startIndex = index;
if (startIndex >= userName.Length)
break;
index = userName.IndexOfAny (ReservedUriCharacters, startIndex);
} while (index != -1);
if (index == -1)
escaped.Append (userName, startIndex, userName.Length - startIndex);
return escaped.ToString ();
}