/// <summary> /// Encodes a URL, like System.Web.HttpUtility.UrlEncode /// </summary> /// <returns>The encoded URL</returns> /// <param name="value">The URL fragment to encode</param> /// <param name="encoding">The encoding to use</param> public static string UrlEncode(string value, System.Text.Encoding encoding = null, string spacevalue = "+") { if (value == null) throw new ArgumentNullException("value"); encoding = encoding ?? System.Text.Encoding.UTF8; var encoder = encoding.GetEncoder(); var inbuf = new char[1]; var outbuf = new byte[2]; var shortout = new byte[1]; return RE_ESCAPECHAR.Replace(value, (m) => { if (m.Value == " ") return spacevalue; inbuf[0] = m.Value[0]; try { var len = encoder.GetBytes(inbuf, 0, 1, outbuf, 0, true); if (len == 1) { shortout[0] = outbuf[0]; return "%" + Utility.ByteArrayAsHexString(shortout).ToLower(); } else if (len == 2) return "%u" + Utility.ByteArrayAsHexString(outbuf).ToLower(); } catch { } //Fallback return m.Value; }); }
/// <summary> /// Encodes a URL, like System.Web.HttpUtility.UrlEncode /// </summary> /// <returns>The encoded URL</returns> /// <param name="value">The URL fragment to encode</param> /// <param name="encoding">The encoding to use</param> public static string UrlEncode(string value, System.Text.Encoding encoding = null, string spacevalue = "+") { if (value == null) throw new ArgumentNullException("value"); encoding = encoding ?? System.Text.Encoding.UTF8; var encoder = encoding.GetEncoder(); var inbuf = new char[1]; var outbuf = new byte[4]; return RE_ESCAPECHAR.Replace(value, (m) => { if (m.Value == " ") return spacevalue; inbuf[0] = m.Value[0]; try { var len = encoder.GetBytes(inbuf, 0, 1, outbuf, 0, true); return "%" + BitConverter.ToString(outbuf, 0, len).Replace("-", "%"); } catch { } //Fallback return m.Value; }); }