首页 > 代码库 > C#工具类之字符串扩展类

C#工具类之字符串扩展类

/// <summary>
    /// 字典串帮忙类
    /// </summary>
    public static class StringHelper
    {
        /// <summary>
        /// 以默认编码返回字符串所对应的字节数组
        /// </summary>
        /// <param name="data">字符串</param>
        /// <returns>字节数组</returns>
        public static byte[] GetBytes(this string data)
        {
            return Encoding.Default.GetBytes(data);
        }

        /// <summary>
        /// 以自定义编码返回字符串所对应的字节数组
        /// </summary>
        /// <param name="data">字符串</param>
        /// <param name="encoding">编码</param>
        /// <returns>字节数组</returns>
        public static byte[] GetBytes(this string data, Encoding encoding)
        {
            return encoding.GetBytes(data);
        }

        /// <summary>
        /// 将字符串以Base64方式编码
        /// </summary>
        /// <param name="value">字符串</param>
        /// <returns>Base64编码后的字符串</returns>
        public static string EncodeBase64(this string value)
        {
            return value.EncodeBase64(Encoding.UTF8);
        }

        /// <summary>
        /// 将字符串以Base64方式编码
        /// </summary>
        /// <param name="value">字符串</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>将Base64方式编码后的字符串</returns>
        public static string EncodeBase64(this string value, Encoding encoding)
        {
            encoding = (encoding ?? Encoding.UTF8);
            var bytes = encoding.GetBytes(value);

            return Convert.ToBase64String(bytes);
        }

        /// <summary>
        /// 将Base64方式编码后的字符串解码
        /// </summary>
        /// <param name="encodedValue">Base64方式编码后的字符串</param>
        /// <returns>解码后的字符串</returns>
        public static string DecodeBase64(this string encodedValue)
        {
            return encodedValue.DecodeBase64(Encoding.UTF8);
        }

        /// <summary>
        /// 将Base64方式编码后的字符串解码
        /// </summary>
        /// <param name="encodedValue">Base64方式编码后的字符串</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>解码后的字符串</returns>
        public static string DecodeBase64(this string encodedValue, Encoding encoding)
        {
            encoding = (encoding ?? Encoding.UTF8);
            var bytes = Convert.FromBase64String(encodedValue);

            return encoding.GetString(bytes);
        }
    }

 

C#工具类之字符串扩展类