vb.net - Encode string to UTF-8
84,673
Solution 1
Use UTF8.GetString(Byte[]) method.
Solution 2
We can check if a string is UTF-8 by examining the string BOM value. This is the correct code sample:
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
Author by
thom
Updated on July 09, 2022Comments
-
thom almost 2 years
I've made a class to encode a string
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
Return encodedString.ToString() always returns "System.Byte[]". How could I get the real UTF-8 String?
-
user1703401 almost 13 yearsThere's no point, that just returns the original string. A utf8 encoded string has to stay in a byte array.
-
thom almost 13 yearsAnd how could I check if a string IS utf-8? Thank you.
-
user1703401 almost 13 yearsYou missed the point. That's not possible, a string is always encoded in utf16 in .NET. If you think you got a string that contains utf8 then you surely do not, it is very likely to have gotten mangled in the process.
-
htm11h almost 11 years@Hans your statement is incorrect, there are differenet .net encoding methods for UTF8, UTF16 and UTF32. msdn.microsoft.com/en-us/library/ms404377(v=vs.90).aspx Your comment should be deleted as inaccurate.
-
Chris about 2 yearsWelcome to Stack Overflow. Code is a lot more helpful when it is accompanied by an explanation. Stack Overflow is about learning, not providing snippets to blindly copy and paste. Please edit your question and explain how it answers the specific question being asked. See How to Answer.