How to convert byte array to string

C#ArraysBinaryreader

C# Problem Overview


I created a byte array with two strings. How do I convert a byte array to string?

var binWriter = new BinaryWriter(new MemoryStream());
binWriter.Write("value1");
binWriter.Write("value2");
binWriter.Seek(0, SeekOrigin.Begin);

byte[] result = reader.ReadBytes((int)binWriter.BaseStream.Length);

I want to convert result to a string. I could do it using BinaryReader, but I cannot use BinaryReader (it is not supported).

C# Solutions


Solution 1 - C#

Depending on the encoding you wish to use:

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

Solution 2 - C#

Assuming that you are using UTF-8 encoding:

string convert = "This is the string to be converted";

// From string to byte array
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(convert);

// From byte array to string
string s = System.Text.Encoding.UTF8.GetString(buffer, 0, buffer.Length);

Solution 3 - C#

You can do it without dealing with encoding by using BlockCopy:

char[] chars = new char[bytes.Length / sizeof(char)];
System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
string str = new string(chars);

Solution 4 - C#

To convert the byte[] to string[], simply use the below line.

byte[] fileData; // Some byte array
//Convert byte[] to string[]
var table = (Encoding.Default.GetString(
                 fileData, 
                 0, 
                 fileData.Length - 1)).Split(new string[] { "\r\n", "\r", "\n" },
                                             StringSplitOptions.None);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionOksanaView Question on Stackoverflow
Solution 1 - C#eulerfxView Answer on Stackoverflow
Solution 2 - C#ba0708View Answer on Stackoverflow
Solution 3 - C#HforHishamView Answer on Stackoverflow
Solution 4 - C#Mansoor AliView Answer on Stackoverflow