当前位置: 首页>>代码示例>>C#>>正文


C# Text.UTF8Encoding类代码示例

本文整理汇总了C#中System.Text.UTF8Encoding的典型用法代码示例。如果您正苦于以下问题:C# System.Text.UTF8Encoding类的具体用法?C# System.Text.UTF8Encoding怎么用?C# System.Text.UTF8Encoding使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


System.Text.UTF8Encoding类属于命名空间,在下文中一共展示了System.Text.UTF8Encoding类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: base64Decode

        /// <summary>
        /// Decodes a base64 string into a readable string
        /// </summary>
        /// <param name="data">Data to decode</param>
        /// <returns></returns>
        private string base64Decode(string data)
        {
            //add padding with '=' to string to accommodate C# Base64 requirements
            int strlen = data.Length + (4 - (data.Length % 4));
            char pad = '=';
            string datapad;

            if (strlen == (data.Length + 4))
            {
                datapad = data;
            }
            else
            {
                datapad = data.PadRight(strlen, pad);
            }

            try
            {
                System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
                System.Text.Decoder utf8Decode = encoder.GetDecoder();

                // create byte array to store Base64 string
                byte[] todecode_byte = Convert.FromBase64String(datapad);
                int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
                char[] decoded_char = new char[charCount];
                utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
                string result = new String(decoded_char);
                return result;
            }
            catch (Exception e)
            {
                throw new Exception("Error in base64Decode: " + e.Message);
            }
        }
开发者ID:persn,项目名称:Lommeradaren,代码行数:39,代码来源:GoogleAuthentication.cs

示例2: Serialize

        public override byte[] Serialize()
        {
            //if (SerializeAsBson)
            //{
            //    return CommonUtils.SerializeAsBson(this);
            //}

            using (MemoryStream ms = new MemoryStream())
            {
                var encoder = new System.Text.UTF8Encoding(false);

                //Write Method Line
                WriteText(ms, encoder, String.IsNullOrWhiteSpace(Method) ? "GET" : Method.Trim().ToUpperInvariant());
                WriteSpace(ms);
                WriteText(ms, encoder, String.IsNullOrWhiteSpace(Resource) ? "/" : Resource.Trim());
                WriteSpace(ms);
                WriteText(ms, encoder, "HTTP/");
                WriteText(ms, encoder, String.IsNullOrWhiteSpace(Version) ? "1.1" : Version.Trim());
                WriteNewLine(ms);

                //Write headers
                WriteHeaders(ms, encoder);

                //Write the new line that seperates headers from content
                WriteNewLine(ms);

                //Write Content
                if (Content != null && Content.Length > 0)
                {
                    ms.Write(Content, 0, Content.Length);
                }

                return ms.ToArray();
            }
        }
开发者ID:bestwpw,项目名称:RestBus,代码行数:35,代码来源:HttpRequestPacket.cs

示例3: ReadCsv

        /// <summary>
        /// CSVを読み込み、薬品情報のリストを返す
        /// </summary>
        /// <param name="path">CSVファイルの絶対パス</param>
        /// <returns>薬品情報のリスト</returns>
        static List<Yakuhin> ReadCsv(string path)
        {
            List<Yakuhin> list = new List<Yakuhin>();
            var enc = new System.Text.UTF8Encoding(false);

            using (var reader = new System.IO.StreamReader(path, enc))
            {
                var csv = new CsvHelper.CsvReader(reader);
                while (csv.Read())
                {
                    string drugCode = csv.GetField<string>(0);
                    string clsCode = csv.GetField<string>(1);
                    string clsName = csv.GetField<string>(2);
                    string drugName = csv.GetField<string>(3);
                    string company = csv.GetField<string>(4);

                    var yakuhin = new Yakuhin
                    {
                        DrugCode = drugCode,
                        ClassificationCode = clsCode,
                        ClassificationName = clsName,
                        DrugName = drugName,
                        Company = company
                    };

                    list.Add(yakuhin);
                }
            }

            return list;
        }
开发者ID:Kazunori-Kimura,项目名称:how-to-develop-dot-net-apps,代码行数:36,代码来源:Program.cs

示例4: getHash

		private string getHash(string s)
		{
			var csp = new System.Security.Cryptography.SHA256Managed();
			var utf8Encoding = new System.Text.UTF8Encoding();
			byte[] result = csp.ComputeHash(utf8Encoding.GetBytes(s));
			return Convert.ToBase64String(result)+"\n";
		}
开发者ID:LearningRegistry,项目名称:LR.Net,代码行数:7,代码来源:CryptoUtils.cs

示例5: UncompressContent

        public static string UncompressContent(byte[] zippedContent)
        {
            try
            {
                MemoryStream inp = new MemoryStream(zippedContent);
                ZipInputStream zipin = new ZipInputStream(inp);
                ZipEntry entryin = zipin.GetNextEntry();
                byte[] buffout = new byte[(int)zipin.Length];
                zipin.Read(buffout, 0, (int)zipin.Length);

                MemoryStream decompress = new MemoryStream(buffout);

                System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
                
                string result = enc.GetString(decompress.ToArray());
                decompress.Dispose();
                inp.Dispose();

                return result;
            }
            catch (Exception ex)
            {
                ex.Message.ToString();
                return null;
            }

        }
开发者ID:Chanicua,项目名称:GoogleHC,代码行数:27,代码来源:CompressionHelper.cs

示例6: DecryptString

        /// <summary>
        /// Decrypt
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public static string DecryptString(string message)
        {
            byte[] results;
            var utf8 = new System.Text.UTF8Encoding();

            var hashProvider = new MD5CryptoServiceProvider();
            var tdesKey = hashProvider.ComputeHash(utf8.GetBytes(Pass));

            var tdesAlgorithm = new TripleDESCryptoServiceProvider
                {
                    Key = tdesKey,
                    Mode = CipherMode.ECB,
                    Padding = PaddingMode.PKCS7
                };

            var dataToDecrypt = Convert.FromBase64String(message);

            try
            {
                var decryptor = tdesAlgorithm.CreateDecryptor();
                results = decryptor.TransformFinalBlock(dataToDecrypt, 0, dataToDecrypt.Length);
            }
            finally
            {
                
                tdesAlgorithm.Clear();
                hashProvider.Clear();
            }

            return utf8.GetString(results);
        }
开发者ID:nhanthieugia,项目名称:BSC.ServiceAPI,代码行数:36,代码来源:CommonLib.cs

示例7: build_page_1

        private void build_page_1()
        {
            TextView tv1 = new TextView ();

            try
            {
                string rez = "Adeptus.Resources.resources";
                string key = "mystring1";
                string resourceType = "";
                byte[] resourceData;
                ResourceReader r = new ResourceReader(rez);
                r.GetResourceData (key, out resourceType, out resourceData);
                r.Close();
                System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
                tv1.Buffer.Text = enc.GetString (resourceData);
            }
            catch (Exception exp)
            {
                tv1.Buffer.Text = exp.Message;
            }

            tv1.WrapMode = WrapMode.Word;
            tv1.Editable = false;

            this.AppendPage (tv1);
            this.SetPageTitle (tv1, "Introduction");
            this.SetPageType (tv1, AssistantPageType.Intro);
            this.SetPageComplete (tv1, true);
        }
开发者ID:sgtnasty,项目名称:battle,代码行数:29,代码来源:NewCharacterWindow.cs

示例8: buildSignature

        private static string buildSignature(NameValueCollection queryString)
        {
            try
            {

            //// The HMAC secret as configured in the skin
                string hmacSecret = Globals.Instance.settings["PayPalhmacSecret"];

            //// Generate the signing string
            string signingString = queryString["paymentAmount"] + queryString["currencyCode"] +
                                   queryString["shipBeforeDate"] + queryString["merchantReference"] +
                                   queryString["skinCode"] + queryString["merchantAccount"] +
                                   queryString["sessionValidity"] + queryString["allowedMethods"] + queryString["merchantReturnData"];

            //// Values are always transferred using UTF-8 encoding
            var encoding = new System.Text.UTF8Encoding();

            //// Calculate the HMAC
            var myhmacsha1 = new HMACSHA1(encoding.GetBytes(hmacSecret));
            return Convert.ToBase64String(myhmacsha1.ComputeHash(encoding.GetBytes(signingString)));
                }
            catch (Exception exp)
            {
                log.Error(exp);
                throw;
            }
        }
开发者ID:HarryMcCarney,项目名称:HackandCraft,代码行数:27,代码来源:PaypalBuilder.cs

示例9: EncryptData

 /// <summary>
 /// MD5 Hash
 /// </summary>
 /// <param name="data"></param>
 /// <returns></returns>
 private static byte[] EncryptData(string data)
 {
     var md5Hasher = new System.Security.Cryptography.MD5CryptoServiceProvider();
     var encoder = new System.Text.UTF8Encoding();
     var hashedBytes = md5Hasher.ComputeHash(encoder.GetBytes(data));
     return hashedBytes;
 }
开发者ID:nhanthieugia,项目名称:BSC.ServiceAPI,代码行数:12,代码来源:CommonLib.cs

示例10: Encrypt

        /// encrypt a string message using a secret key that is known to both sender and recipient only;
        /// need to give the initialization vector to the recipient as well;
        static public bool Encrypt(byte[] ASecretKey, string AMessage, out string AEncryptedMessage, out string AInitializationVector)
        {
            Rijndael alg = new RijndaelManaged();

            alg.Key = ASecretKey;

            alg.GenerateIV();

            MemoryStream ms = new MemoryStream();

            CryptoStream encryptStream = new CryptoStream(
                ms,
                alg.CreateEncryptor(),
                CryptoStreamMode.Write);

            System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
            byte[] toEncryptBytes = enc.GetBytes(AMessage);
            encryptStream.Write(toEncryptBytes, 0, toEncryptBytes.Length);
            encryptStream.Close();

            AEncryptedMessage = Convert.ToBase64String(ms.ToArray());
            AInitializationVector = Convert.ToBase64String(alg.IV);

            return true;
        }
开发者ID:Davincier,项目名称:openpetra,代码行数:27,代码来源:Encryption.cs

示例11: MakeRequest

        public void MakeRequest(string type, string platform, string reqjsondata)
        {
            System.Text.UTF8Encoding en = new System.Text.UTF8Encoding();

            string secret = Configs.Secret;

            string uri = "http://api.bf3stats.com/" + platform + "/" + type + "/";
            WebClient wc = new WebClient();
            wc.Headers["Content-Type"] = "application/x-www-form-urlencoded";

            if (type == "setupkey")
            {
                wc.UploadStringCompleted += new UploadStringCompletedEventHandler(completed_register);
            }
            else
            {
                wc.UploadStringCompleted += new UploadStringCompletedEventHandler(completed_update);
                secret = Configs.GetAPIkey();
            }

            System.Security.Cryptography.HMACSHA256 hmac = new System.Security.Cryptography.HMACSHA256(en.GetBytes(secret));

            Byte[] bytes = en.GetBytes(reqjsondata);
            string encodedRequest = Convert.ToBase64String(bytes).Replace('+', '-').Replace('/', '_').Replace("=", "");

            byte[] hashVal = hmac.ComputeHash(en.GetBytes(encodedRequest));
            string signature = Convert.ToBase64String(hashVal).Replace('+', '-').Replace('/', '_').Replace("=", "");

            string query = "data=" + encodedRequest + "&sig=" + signature;
            wc.UploadStringAsync(new Uri(uri), "POST", query);
        }
开发者ID:graboskyc,项目名称:BFStats,代码行数:31,代码来源:SignedRequest.cs

示例12: ComputeHashString

 protected string ComputeHashString(string rawString)
 {
     System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
     SHA256 hashM = new SHA256Managed();
     return encoding.GetString(hashM.ComputeHash(encoding.GetBytes(rawString))).
         Replace(',', '.').Replace('\r', '.').Replace('\n', '.');
 }
开发者ID:ne-sachirou,项目名称:yUsin-1,代码行数:7,代码来源:DatasData.cs

示例13: CompressContent

        /// <summary>
        /// Compress an string using ZIP
        /// </summary>
        /// <param name="xml"></param>
        /// <returns></returns>
        public static byte[] CompressContent(string contentToZip)
        {

            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            byte[] buff = encoding.GetBytes(contentToZip);

            try
            {
                using (MemoryStream stream = new MemoryStream())
                {
                    using (ZipOutputStream zipout = new ZipOutputStream(stream))
                    {
                        zipout.SetLevel(9);
                        ZipEntry entry = new ZipEntry("zipfile.zip");
                        entry.DateTime = DateTime.Now;
                        zipout.PutNextEntry(entry);
                        zipout.Write(buff, 0, buff.Length);
                        zipout.Finish();
                        byte[] outputbyte = new byte[(int)stream.Length];
                        stream.Position = 0;
                        stream.Read(outputbyte, 0, (int)stream.Length);
                        return outputbyte;
                    }

                }
            }
            catch (Exception ex)
            {
                ex.Message.ToString();
                return null;
            }
        }
开发者ID:Chanicua,项目名称:GoogleHC,代码行数:37,代码来源:CompressionHelper.cs

示例14: Base64Decode

 /// <summary>
 /// Base64解密
 /// </summary>
 /// <param name="Message">需要解密的字符串</param>
 /// <returns></returns>
 public string Base64Decode(string Message)
 {
     try
     {
         string result = "";
         if (isEncrypt)
         {
             Message = Message.Replace(" ", "+");
             string gbStr = System.Text.Encoding.GetEncoding("utf-8").GetString(System.Text.Encoding.Default.GetBytes(Message));
             System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
             System.Text.Decoder utf8Decode = encoder.GetDecoder();
             byte[] todecode_byte = Convert.FromBase64String(Message);
             int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
             char[] decoded_char = new char[charCount];
             utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
             result = new String(decoded_char);
         }
         else
         {
             result = Message;
         }
         return result;
     }
     catch (Exception e)
     {
         throw new Exception("Error in base64Decode" + e.Message);
     }
 }
开发者ID:codefighting,项目名称:shouxinzhihui,代码行数:33,代码来源:Base64Manager.cs

示例15: WriteLongString

 public void WriteLongString(string str)
 {
     var encoding = new System.Text.UTF8Encoding();
     var bytes = encoding.GetBytes(str);
     WriteInt32(bytes.Length);
     _base.Write(bytes);
 }
开发者ID:joaquincasares,项目名称:csharp-driver,代码行数:7,代码来源:BEBinaryWriter.cs


注:本文中的System.Text.UTF8Encoding类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。