This question already has answers here: How to convert UTF-8 byte[] to string (16 answers) Closed 8 years ago.
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).
new String(result)
Depending on the encoding you wish to use:
var str = System.Text.Encoding.Default.GetString(result);
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);
System.Text.Encoding.UTF8.GetString(buffer, 0, buffer.Length);
bring compared to System.Text.Encoding.UTF8.GetString(buffer);
?
BitConverter.ToString(byteArray))
docs.microsoft.com/en-us/dotnet/api/…
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);
Math.Ceiling
on bytes.Length / sizeof(char)
then it will always work correctly.
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);
Success story sharing
System.Text.Encoding.Default
is the system's current ANSI code page - the results of this will vary depending on how the operating system is configured. If you know what encoding the string really is you should use that one instead.