netnr/ ToEncode-ToDecode.cs 2018-11-03 10:12
编码、解码
/// <summary>
/// 编码
/// </summary>
/// <param name="uri"></param>
/// <param name="charset"></param>
/// <returns></returns>
public static string ToEncode(this string uri, string charset = "utf-8")
{
    string URL_ALLOWED_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~";

    if (string.IsNullOrEmpty(uri))
        return string.Empty;

    const string escapeFlag = "%";
    var encodedUri = new StringBuilder(uri.Length * 2);
    var bytes = Encoding.GetEncoding(charset).GetBytes(uri);
    foreach (var b in bytes)
    {
        char ch = (char)b;
        if (URL_ALLOWED_CHARS.IndexOf(ch) != -1)
            encodedUri.Append(ch);
        else
        {
            encodedUri.Append(escapeFlag).Append(string.Format(CultureInfo.InstalledUICulture, "{0:X2}", (int)b));
        }
    }
    return encodedUri.ToString();
}

/// <summary>
/// 解码
/// </summary>
/// <param name="uriToDecode"></param>
/// <returns></returns>
public static string ToDecode(this string uriToDecode)
{
    if (!string.IsNullOrEmpty(uriToDecode))
    {
        uriToDecode = uriToDecode.Replace("+", " ");
        return Uri.UnescapeDataString(uriToDecode);
    }

    return string.Empty;
}