2011-05-17 482 views
2

我做了一個類來編碼字符串vb.net - 編碼字符串轉換爲UTF-8

Public Class UTF8 
    Public Shared Function encode(ByVal str As String) 
     Dim utf8Encoding As New System.Text.UTF8Encoding 
     Dim encodedString() As Byte 

     encodedString = utf8Encoding.GetBytes(str) 

     Return encodedString.ToString() 
    End Function 
End Class 

返回encodedString.ToString()總是返回 「System.Byte []」。我怎樣才能得到真正的UTF-8字符串?

回答

4

使用UTF8.GetString(Byte[])方法。

+1

沒有意義,那只是返回原始字符串。一個utf8編碼的字符串必須保留在一個字節數組中。 – 2011-05-17 18:52:03

+0

如何檢查字符串是否是utf-8?謝謝。 – thom 2011-05-17 19:08:38

+0

你錯過了這一點。這是不可能的,一個字符串總是用.NET中的utf16編碼。如果你認爲你得到了一個包含utf8的字符串,那麼你肯定不會這樣做,這很可能在這個過程中發生了重大變化。 – 2011-05-17 20:07:27

2

我們可以通過檢查字符串BOM值來檢查字符串是否爲UTF-8。這是正確的代碼示例:

Public Shared Function encode(ByVal str As String) As String 
    'supply True as the construction parameter to indicate 
    'that you wanted the class to emit BOM (Byte Order Mark) 
    'NOTE: this BOM value is the indicator of a UTF-8 string 
    Dim utf8Encoding As New System.Text.UTF8Encoding(True) 
    Dim encodedString() As Byte 

    encodedString = utf8Encoding.GetBytes(str) 

    Return utf8Encoding.GetString(encodedString) 
End Function