Home > Software engineering >  How to convert byte[] to string?
How to convert byte[] to string?

Time:09-12

I have an API which reads an uploaded Image and changes it to a byte[], however in the database the field for where I have to save the image is a string instead of varbinary(MAX), and I cannot change the field type of the database.

I thought about converting the image to base64 and then storing it but this might cause unnecessary strain on the database.

I have found online the following way but this method can be inconsistent based on the server as the encoding might change:

var str = System.Text.Encoding.Default.GetString(result);

And if I were to use the above method I would need to know what type of encoding does ReadBytes use.

Below is my code:

byte[] fileData = null;
using (var binaryReader = new BinaryReader(image.InputStream))
{
      binaryReader.BaseStream.Position = 0;
      fileData = binaryReader.ReadBytes(image.ContentLength);
}                       

Furthermore, when I converted the image to a base64 and viewed it, only have the image was visible:

var base64String = Convert.ToBase64String(fileData);

CodePudding user response:

use Convert.toBase64String() method or just using MemoryStream class->

// 1.toBase64String()
string str = Convert.ToBase64String(bytes);
// 2.MemoryStream class
using (MemoryStream stream = new MemoryStream(bytes))
using (StreamReader streamReader = new StreamReader(stream))
{
    return streamReader.ReadToEnd();
}

CodePudding user response:

Initialize the BinaryReader with this overload that specifies the encoding.

var binaryReader = new BinaryReader(System.IO.Stream input, System.Text.Encoding encoding);
  • Related