Convert a Base64-encoded byte array to string in CSharp

Description

The following code shows how to convert a Base64-encoded byte array to string.

Example


  /*from w  w  w  .ja  va2  s . c om*/
  
  
   

using System;
using System.Data;
using System.Text.RegularExpressions;
using System.Text;
class Class1{
        static void Main(string[] args){
             Console.WriteLine(Base64EncodeBytes(new byte[5] {45,34,23,54,38}));
         }
    public static string Base64EncodeBytes(byte[] inputBytes) 
    {
      // Each 3 byte sequence in inputBytes must be converted to a 4 byte sequence 
      long arrLength = (long)(4.0d * inputBytes.Length / 3.0d);
      if ((arrLength  % 4) != 0) 
      {
        // increment the array lenght to the next multiple of 4 if it is not already divisible by 4
        arrLength += 4 - (arrLength % 4);
      }
    
      char[] encodedCharArray = new char[arrLength];
      Convert.ToBase64CharArray(inputBytes, 0, inputBytes.Length, encodedCharArray, 0);
      
      return (new string(encodedCharArray));
    }      
}

The code above generates the following result.





















Home »
  C# Tutorial »
    Data Types »




C# Data Types
Bool
Byte
Char
Decimal
Double
Float
Integer
Long
Short
String
C# Array
Array Example
Byte Array
C# Standard Data Type Format
BigInteger
Complex
Currency
DateTime
DateTimeOffset
DateTime Format Parse Convert
TimeSpan
TimeZone
Enum
Null
tuple
var