C#でUrlEncodeとUrlDecode
2018年8月13日 (月) 04:40時点におけるimported>Administratorによる版 (ページの作成:「C#というか.NETにはUrlEncodeとUrlDecodeの統一的な方法がない。標準的に行う方法は、バージョンごと、プラットフォームごとに方...」)
C#というか.NETにはUrlEncodeとUrlDecodeの統一的な方法がない。標準的に行う方法は、バージョンごと、プラットフォームごとに方法が異なりすぎて悲惨なことになっている。
public static string UrlEncode( string s , Encoding enc )
{
StringBuilder rt = new StringBuilder();
foreach ( byte i in enc.GetBytes( s ) )
{
if ( i == 0x20 )
{
rt.Append( '+' );
}
else if ( (0x30 <= i && i <= 0x39) || (0x41 <= i && i <= 0x5a) || (0x61 <= i && i <= 0x7a) )
{
rt.Append( (char)i );
}
else
{
rt.Append( "%" + i.ToString( "X2" ) );
}
}
return rt.ToString();
}
public static string UrlDecode( string s , Encoding enc )
{
List<byte> bytes = new List<byte>();
for ( int i = 0; i < s.Length; i++ )
{
char c = s[i];
if ( c == '%' )
{
bytes.Add( (byte)int.Parse( s[++i].ToString() + s[++i].ToString() , System.Globalization.NumberStyles.HexNumber ) );
}
else if ( c == '+' )
{
bytes.Add( (byte)0x20 );
}
else
{
bytes.Add( (byte)c );
}
}
return enc.GetString( bytes.ToArray() , 0 , bytes.Count );
}