URL Encode all non alpha numeric in C#

后端 未结 4 1436
轻奢々
轻奢々 2021-01-12 11:01

I need to fully URL Encode an email address.

HttpUtility.UrlEncode seems to ignore certain characters such as ! and .

I need to pass an email address in a ur

4条回答
  •  梦谈多话
    2021-01-12 11:33

    Use hex. There is a ConvertTo and a From and a sample test...

    You can also just scape the characters that don't match A to Z by using a regex so your URL still looks pretty.

    It will return a big list of numbers so you should be good

            public static string ConvertToHex(string asciiString)
        {
            var hex = "";
            foreach (var c in asciiString)
            {
                int tmp = c;
                hex += String.Format("{0:x2}", Convert.ToUInt32(tmp.ToString()));
            }
            return hex;
        }
    
        public static string ConvertToString(string hex)
        {
            var stringValue = "";
            // While there's still something to convert in the hex string
            while (hex.Length > 0)
            {
                stringValue += Convert.ToChar(Convert.ToUInt32(hex.Substring(0, 2), 16)).ToString();
                // Remove from the hex object the converted value
                hex = hex.Substring(2, hex.Length - 2);
            }
    
            return stringValue;
        }
    
        static void Main(string[] args)
        {
            string hex = ConvertToHex("don.joe@gmail.com");
            Console.WriteLine(hex);
            Console.ReadLine();
            string stringValue =
            ConvertToString(hex);
            Console.WriteLine(stringValue);
            Console.ReadLine();
    
        }
    

提交回复
热议问题