Esempio n. 1
0
        public static byte[] EncodeMessage(string content)
        {
            byte[] cont = new byte[content.Length];

            System.Text.ASCIIEncoding coidn = new System.Text.ASCIIEncoding();
            System.Text.Encoder       enc   = coidn.GetEncoder();
            int  charsconv = 0;
            int  bytesconv = 0;
            bool conv      = false;

            enc.Convert(content.ToCharArray(), 0, content.Length, cont, 0, cont.Length, true, out charsconv, out bytesconv, out conv);

            return(cont);
        }
Esempio n. 2
0
        /// <summary>
        /// URL编码
        /// </summary>
        /// <param name="str"></param>
        /// <param name="encode"></param>
        /// <returns></returns>
        private static string UrlEncode(string str, string encode)
        {
            int factor = 0;

            if (encode == "UTF-8")
            {
                factor = 3;
            }
            if (encode == "GB2312")
            {
                factor = 2;
            }
            //不需要编码的字符

            string okChar = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.=";

            System.Text.Encoder encoder = System.Text.Encoding.GetEncoding(encode).GetEncoder();
            char[] c1 = str.ToCharArray();
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            //一个字符一个字符的编码

            for (int i = 0; i < c1.Length; i++)
            {
                //不需要编码

                if (okChar.IndexOf(c1[i]) > -1)
                {
                    sb.Append(c1[i]);
                }
                else
                {
                    byte[] c2 = new byte[factor];
                    int    charUsed, byteUsed; bool completed;

                    encoder.Convert(c1, i, 1, c2, 0, factor, true, out charUsed, out byteUsed, out completed);

                    foreach (byte b in c2)
                    {
                        if (b != 0)
                        {
                            sb.AppendFormat("%{0:X}", b);
                        }
                    }
                }
            }
            return(sb.ToString().Trim());
        }