using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UnitTestProject1 { public static class WebUnit { public static string UrlEncode(string value) { if (value == null) { return null; } byte[] bytes = Encoding.UTF8.GetBytes(value); return Encoding.UTF8.GetString(UrlEncode(bytes, 0, bytes.Length, alwaysCreateNewReturnValue: false)); } private static byte[] UrlEncode(byte[] bytes, int offset, int count, bool alwaysCreateNewReturnValue) { byte[] array = UrlEncode(bytes, offset, count); if (!alwaysCreateNewReturnValue || array == null || array != bytes) { return array; } return (byte[])array.Clone(); } private static byte[] UrlEncode(byte[] bytes, int offset, int count) { if (!ValidateUrlEncodingParameters(bytes, offset, count)) { return null; } int num = 0; int num2 = 0; for (int i = 0; i < count; i++) { char c = (char)bytes[offset + i]; if (c == ' ') { num++; } else if (!IsUrlSafeChar(c)) { num2++; } } if (num == 0 && num2 == 0) { if (offset == 0 && bytes.Length == count) { return bytes; } byte[] array = new byte[count]; Buffer.BlockCopy(bytes, offset, array, 0, count); return array; } byte[] array2 = new byte[count + num2 * 2]; int num3 = 0; for (int j = 0; j < count; j++) { byte b = bytes[offset + j]; char c2 = (char)b; if (IsUrlSafeChar(c2)) { array2[num3++] = b; continue; } if (c2 == ' ') { array2[num3++] = 43; continue; } array2[num3++] = 37; array2[num3++] = (byte)IntToHex((b >> 4) & 0xF); array2[num3++] = (byte)IntToHex(b & 0xF); } return array2; } private static char IntToHex(int n) { if (n <= 9) { return (char)(n + 48); } return (char)(n - 10 + 65); } private static bool ValidateUrlEncodingParameters(byte[] bytes, int offset, int count) { if (bytes == null && count == 0) { return false; } if (bytes == null) { throw new ArgumentNullException("bytes"); } if (offset < 0 || offset > bytes.Length) { throw new ArgumentOutOfRangeException("offset"); } if (count < 0 || offset + count > bytes.Length) { throw new ArgumentOutOfRangeException("count"); } return true; } private static bool IsUrlSafeChar(char ch) { if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9')) { return true; } switch (ch) { case '!': case '(': case ')': case '*': case '-': case '.': case '_': return true; default: return false; } } } }