CSharp examples for System:String Encode Decode
Encodes a URL string. These method overloads can be used to encode the entire URL, including query-string values.
// Copyright (c) Microsoft Corporation. All rights reserved. using System.Text; using System;/* ww w . ja v a 2 s. c om*/ public class Main{ /// <summary> /// Encodes a URL string. These method overloads can be used to encode the entire URL, including query-string values. /// </summary> /// <remarks> /// (c) Microsoft Corporation 2013. Code ported from .NET 4.5 4.5.50709.0. /// </remarks> /// <param name="bytes"></param> /// <param name="offset"></param> /// <param name="count"></param> /// <returns></returns> public static byte[] UrlEncode( byte[] bytes, int offset, int count ) { if( !ValidateUrlEncodingParameters( bytes, offset, count ) ) { return null; } int cSpaces = 0; int cUnsafe = 0; // count them first for( int i = 0; i < count; i++ ) { char ch = (char)bytes[offset + i]; if( ch == ' ' ) cSpaces++; else if( !HttpEncoderUtility.IsUrlSafeChar( ch ) ) cUnsafe++; } // nothing to expand? if( cSpaces == 0 && cUnsafe == 0 ) return bytes; // expand not 'safe' characters into %XX, spaces to +s byte[] expandedBytes = new byte[count + cUnsafe * 2]; int pos = 0; for( int i = 0; i < count; i++ ) { byte b = bytes[offset + i]; char ch = (char)b; if( HttpEncoderUtility.IsUrlSafeChar( ch ) ) { expandedBytes[pos++] = b; } else if( ch == ' ' ) { expandedBytes[pos++] = (byte)'+'; } else { expandedBytes[pos++] = (byte)'%'; expandedBytes[pos++] = (byte)HttpEncoderUtility.IntToHex( ( b >> 4 ) & 0xf ); expandedBytes[pos++] = (byte)HttpEncoderUtility.IntToHex( b & 0x0f ); } } return expandedBytes; } /// <summary> /// Encodes a URL string. These method overloads can be used to encode the entire URL, including query-string values. /// </summary> /// <remarks> /// (c) Microsoft Corporation 2013. Code ported from .NET 4.5 4.5.50709.0. /// </remarks> /// <param name="bytes"></param> /// <returns></returns> public static string UrlEncode( byte[] bytes ) { if( bytes == null ) return null; byte[] output = UrlEncode( bytes, 0, bytes.Length ); return Encoding.UTF8.GetString( output, 0, output.Length ); } /// <summary> /// Encodes a URL string. These method overloads can be used to encode the entire URL, including query-string values. /// </summary> /// <remarks> /// (c) Microsoft Corporation 2013. Code ported from .NET 4.5 4.5.50709.0. /// </remarks> /// <param name="bytes"></param> /// <returns></returns> public static string UrlEncode( string str ) { if( str == null ) return null; byte[] bytes = Encoding.UTF8.GetBytes( str ); byte[] output = UrlEncode( bytes, 0, bytes.Length ); return Encoding.UTF8.GetString( output, 0, output.Length ); } }