.NET在winform中使用UrlEncode进行字符串编码字母大写

.NET UrlEncode方法编码的字符串结果都是小写字母,为了在winform中使用该方法,而不去引用多余的程序集,比如system.web等等,故将此方法提取出来稍作修改,这样编码后的字符串结果所有字母就是大写的了。如下~分享之。。效率应该比外面流传的要快一些吧

public static string UrlEncode( string str ) {
            return UrlEncode( str, System.Text.Encoding.UTF8 );
        }
        public static string UrlEncode( string str, Encoding e ) {
            if (str == null) {
                return null;
            }
            return Encoding.ASCII.GetString( UrlEncodeToBytes( str, e ) );
        }
        private static byte[] UrlEncodeToBytes( string str, Encoding e ) {
            if (str == null) {
                return null;
            }
            byte[] bytes = e.GetBytes( str );
            return UrlEncodeBytesToBytesInternal( bytes, 0, bytes.Length, false );
        }
        private static byte[] UrlEncodeBytesToBytesInternal( byte[] bytes, int offset, int count, bool alwaysCreateReturnValue ) {
            int num = 0;
            int num2 = 0;
            for (int i = 0; i < count; i++) {
                char ch = (char)bytes[offset + i];
                if (ch == ' ') {
                    num++;
                }
                else if (!IsSafe( ch )) {
                    num2++;
                }
            }
            if ((!alwaysCreateReturnValue && (num == 0)) && (num2 == 0)) {
                return bytes;
            }
            byte[] buffer = new byte[count + (num2 * 2)];
            int num4 = 0;
            for (int j = 0; j < count; j++) {
                byte num6 = bytes[offset + j];
                char ch2 = (char)num6;
                if (IsSafe( ch2 )) {
                    buffer[num4++] = num6;
                }
                else if (ch2 == ' ') {
                    buffer[num4++] = 43;
                }
                else {
                    buffer[num4++] = 37;
                    buffer[num4++] = (byte)IntToHex( (num6 >> 4) & 15 );
                    buffer[num4++] = (byte)IntToHex( num6 & 15 );
                }
            }
            return buffer;
        }
        private static bool IsSafe( 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 '_':
                case '!':
                    return true;
            }
            return false;
        }
        private static char IntToHex( int n ) {
            if (n <= 9) {
                return (char)(n + 48);
            }
            return (char)((n - 10) + 65);
        }
作者:一修先生
         
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/1971ruru/p/2514923.html