thom
thom

Reputation: 85

vb.net - Encode string to UTF-8

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?

Upvotes: 2

Views: 99966

Answers (3)

ritm0o
ritm0o

Reputation: 1

Public Class Form1


    Private Sub BtnClearText_Click(sender As Object, e As EventArgs) Handles BtnClearText.Click
        TxtEncodedValue.Text = ""
        TxtNormalValue.Text = ""
    End Sub

    Private Sub BtnEncode_Click(sender As Object, e As EventArgs) Handles BtnEncode.Click
        Dim byt As Byte() = System.Text.Encoding.UTF8.GetBytes(TxtNormalValue.Text)
        TxtEncodedValue.Text = Convert.ToBase64String(byt)
    End Sub

    Private Sub BtnDecode_Click(sender As Object, e As EventArgs) Handles BtnDecode.Click
        Dim b As Byte() = Convert.FromBase64String(TxtEncodedValue.Text)
        TxtNormalValue.Text = System.Text.Encoding.UTF8.GetString(b)
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    End Sub

 
End Class

Upvotes: 0

Predator
Predator

Reputation: 1275

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

Upvotes: 2

Alireza Maddah
Alireza Maddah

Reputation: 5885

Use UTF8.GetString(Byte[]) method.

Upvotes: 4

Related Questions