2009年2月27日 星期五

asp.net中cookie的亂碼解決方法

參考網址:..不見了!?

在asp.net中,中文字(非英文字?)存入cookies,再次取出會有亂碼問題,所以要使用
HttpUtility.UrlEncode和HttpUtility.UrlDecode對cookies內容編碼
PS: 需引用system.text

進階參考
* Encoding.Convert 方法
* 使用Unicode 編碼方式
ASP.Net 的 UTF-8 轉 Big5
VB中則可使用 StringS.strConv <--注意S而不是常用String
PS: imports microsoft.visualbasic


即用範例
Imports System

Imports System.Text
Imports Microsoft.VisualBasic

Namespace Convert_Example
Class MyConvertExampleClass
Shared Sub Main()
Dim unicodeString As String = "This string contains the unicode character Pi(" & ChrW(&H03A0) & ")"

' Create two different encodings. ASCII與 Unicode兩者互轉
Dim ascii As Encoding = Encoding.ASCII
Dim [unicode] As Encoding = Encoding.Unicode

' Convert the string into a byte[].
Dim unicodeBytes As Byte() = [unicode].GetBytes(unicodeString)

' Perform the conversion from one encoding to the other. 這段程式很麻煩,一定要先用Byte型態之後,才能轉碼!
Dim asciiBytes As Byte() = Encoding.Convert([unicode], ascii, unicodeBytes)


' Convert the new byte[] into a char[] and then into a string.
' This is a slightly different approach to converting to illustrate
' the use of GetCharCount/GetChars.
Dim asciiChars(ascii.GetCharCount(asciiBytes, 0, asciiBytes.Length)) As Char
ascii.GetChars(asciiBytes, 0, asciiBytes.Length, asciiChars, 0)
Dim asciiString As New String(asciiChars)

' Display the strings created before and after the conversion.
Console.WriteLine("Original string: {0}", unicodeString)
Console.WriteLine("Ascii converted string: {0}", asciiString)
End Sub
End Class
End Namespace