Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET: Why isn't base 64 in Encoding.GetEncodings()?

I have a function that can decode an array of bytes into a string of characters using a specified encoding.

Example:

Function Decode(ByVal bytes() As Byte, ByVal codePage As String) As String
    Dim enc As Text.Encoding = Text.Encoding.GetEncoding(codePage)
    Return enc.GetString(bytes)
End Function

If I want to include base64 in this I have to do something like this:

Function Decode(ByVal bytes() As Byte, ByVal codePage As String) As String
    If String.Compare(codePage, "base64", True) = 0 Then
        Return Convert.ToBase64String(bytes)
    Else
        Dim enc As Text.Encoding = Text.Encoding.GetEncoding(codePage)
        Return enc.GetString(bytes)
    End If
End Function

Why is base64 treated special in .NET?

like image 970
Rob Sobers Avatar asked Nov 30 '22 20:11

Rob Sobers


1 Answers

They're really not the same thing:

  • Encodings are ways of representing arbitrary text in binary form.
  • Base64 is a way of representing arbitrary binary data in text form.

You wouldn't normally use them in the same circumstances. You'd use an encoding when the "real" data is text, and base64 when the "real" data is binary.

Of course you could implement an encoding to do base64, but personally I don't think it's a good idea.

like image 195
Jon Skeet Avatar answered Dec 04 '22 23:12

Jon Skeet