Question

How to Convert a Byte Array to a String in C#

csharparraysbinaryreader

Question

I created a byte array by writing two strings into a MemoryStream using BinaryWriter. How can I convert that byte array back into a string?

var stream = new MemoryStream();
var binWriter = new BinaryWriter(stream);

binWriter.Write("value1");
binWriter.Write("value2");
binWriter.Seek(0, SeekOrigin.Begin);

byte[] result = stream.ToArray();

I want to convert result to a string. I know this could be read back using BinaryReader, but I cannot use BinaryReader in my environment. How can I correctly convert the byte array to a string?

Short Answer

By the end of this page, you will understand how byte arrays and strings relate in C#, why encoding matters, and why bytes written with BinaryWriter.Write(string) are not always the same as plain text bytes. You will also learn the correct way to turn raw text bytes into a string and how to avoid common decoding mistakes.

Concept

In C#, a string is text, while a byte[] is raw binary data. To convert between them, you need an encoding such as UTF-8 or UTF-16. The encoding defines how characters are represented as bytes.

A common beginner assumption is that any byte[] containing text can be turned into a string directly. That is only true if the bytes were originally produced as text bytes using a known encoding.

In your example, the important detail is this:

binWriter.Write("value1");
binWriter.Write("value2");

BinaryWriter.Write(string) does not simply write the characters one after another as plain text. It writes the string in a binary format that includes length information before the characters. That means the resulting byte array is not just:

value1value2

It contains extra bytes that help a BinaryReader reconstruct the strings later.

So there are really two different situations:

  1. The byte array contains plain text bytes
    Use an encoding like Encoding.UTF8.GetString(bytes).

  2. The byte array contains data written in a binary format
    You cannot safely treat it as normal text. You must decode it according to the format that created it.

This matters in real programming because files, network messages, APIs, logs, and serialized data often mix text and binary formats. If you decode bytes using the wrong assumption, you get corrupted text, odd symbols, or unreadable output.

Mental Model

Think of a byte[] as a box of numbered pieces.

  • If the pieces were packed using a known text alphabet like UTF-8, you can read them as a sentence.
  • If the pieces were packed using a binary storage format, some pieces are instructions, sizes, or metadata, not actual text.

BinaryWriter.Write(string) is like putting each word in a package with a label showing its length. If you dump all the package contents and try to read them as one plain sentence, the labels get mixed into the text.

So the key question is not just how do I turn bytes into a string? but what do these bytes actually represent?

Take Quiz

Syntax and Examples

If your byte array contains plain text bytes, convert it like this:

using System.Text;

byte[] bytes = Encoding.UTF8.GetBytes("Hello world");
string text = Encoding.UTF8.GetString(bytes);

Console.WriteLine(text); // Hello world

Example with two strings combined as text

If your goal is to store two strings as normal text, combine them first and then encode them:

using System.Text;

string combined = "value1 value2";
byte[] bytes = Encoding.UTF8.GetBytes(combined);
string text = Encoding.UTF8.GetString(bytes);

Console.WriteLine(text); // value1 value2

What happens with BinaryWriter

using System;
using System.IO;
using System.Text;

var stream = new MemoryStream();
var writer = new BinaryWriter(stream, Encoding.UTF8);

writer.Write("value1");
writer.Write("value2");
writer.Flush();

byte[] result = stream.ToArray();
string text = Encoding.UTF8.GetString(result);

Console.WriteLine(text);

This may produce output with unexpected characters because the byte array contains binary length prefixes, not just the text itself.

If you only want readable text

Write text bytes directly instead of using BinaryWriter.Write(string):

using System;
using System.IO;
using System.Text;

var stream = new MemoryStream();
byte[] bytes = Encoding.UTF8.GetBytes("value1value2");
stream.Write(bytes, 0, bytes.Length);

string text = Encoding.UTF8.GetString(stream.ToArray());
Console.WriteLine(text); // value1value2

Step by Step Execution

Consider this small example:

using System;
using System.Text;

byte[] bytes = Encoding.UTF8.GetBytes("cat");
string text = Encoding.UTF8.GetString(bytes);

Console.WriteLine(text);

Step by step:

  1. "cat" is a C# string.
  2. Encoding.UTF8.GetBytes("cat") converts each character into UTF-8 bytes.
  3. The byte array now contains the raw byte values for c, a, and t.
  4. Encoding.UTF8.GetString(bytes) reads those bytes using the same UTF-8 rules.
  5. The result becomes the string "cat" again.

Now compare that with BinaryWriter.Write("cat"):

using System;
using System.IO;
using System.Text;

var stream = new MemoryStream();
var writer = new BinaryWriter(stream, Encoding.UTF8);
writer.Write("cat");
writer.Flush();

byte[] data = stream.ToArray();

What gets written is not just the UTF-8 bytes for cat.

It also includes extra information used by the binary format. So if you do this:

string text = Encoding.UTF8.GetString(data);

The decoder tries to interpret every byte as text, including the binary metadata. That is why the result is not reliable plain text.

Real World Use Cases

Converting a byte array to a string is common in many practical situations:

  • Reading API responses: HTTP responses often arrive as bytes and must be decoded using UTF-8.
  • Reading files: Text files are stored as bytes and must be converted to strings with the correct encoding.
  • Logging and debugging: You may inspect raw message payloads by decoding bytes to readable text.
  • Socket communication: Network data is often sent as byte arrays and decoded into commands or JSON.
  • Message queues: Queue systems often send UTF-8 encoded JSON or plain text as bytes.

But binary formats are different:

  • Custom serialization
  • Binary protocols
  • Compressed data
  • Encrypted payloads

These should not be decoded as plain strings unless a specific part is known to be text.

Take Quiz

Real Codebase Usage

In real projects, developers usually make encoding explicit and keep binary data separate from text data.

Common patterns

  • Explicit encoding
string json = Encoding.UTF8.GetString(payloadBytes);

This avoids relying on defaults.

  • Guard clauses for invalid input
if (payloadBytes == null || payloadBytes.Length == 0)
    return string.Empty;
  • Text protocols

When the data is meant to be human-readable, teams often use UTF-8 consistently across files, APIs, and services.

  • Binary protocols

When using BinaryWriter and BinaryReader, developers treat the data as structured binary, not plain text.

  • Validation before decoding

If bytes may not be valid text, developers often validate the source or catch decoding issues when necessary.

A practical helper method

using System.Text;

public static string BytesToUtf8String(byte[] bytes)
{
    if (bytes == null || bytes.Length == 0)
        return string.Empty;

    return Encoding.UTF8.GetString(bytes);
}

This is common when handling API or file content that is guaranteed to be UTF-8.

Common Mistakes

1. Assuming every byte array is text

Broken idea:

string text = Encoding.UTF8.GetString(someBytes);

This only works if someBytes actually contains UTF-8 text.

Avoid it by asking: How were these bytes created?

2. Using BinaryWriter.Write(string) when plain text is needed

Broken example:

var stream = new MemoryStream();
var writer = new BinaryWriter(stream);
writer.Write("hello");

string text = Encoding.UTF8.GetString(stream.ToArray());

This may include unexpected characters because BinaryWriter writes more than just text bytes.

Use this instead if you need plain text bytes:

byte[] bytes = Encoding.UTF8.GetBytes("hello");

3. Mixing encodings

Broken example:

byte[] bytes = Encoding.Unicode.GetBytes("hello");
string text = Encoding.UTF8.GetString(bytes);

The encoding used to decode must match the encoding used to encode.

4. Forgetting to flush the writer

writer.Flush();
byte[] data = stream.ToArray();

Without flushing, recent writes may not be fully committed to the stream.

5. Expecting multiple binary-written strings to become one readable string

If you wrote two separate strings with BinaryWriter, the result is still a binary structure, not automatically a joined text value.

If you need plain text output, create the full string first and then encode it.

Comparisons

ApproachUse whenResultNotes
Encoding.UTF8.GetString(bytes)Bytes are plain UTF-8 textReadable stringBest for text data
Encoding.UTF8.GetBytes(text)You want text as bytesbyte[]Reverse operation
BinaryWriter.Write(string)You want to store strings in a binary formatStructured binary dataIncludes length metadata
StreamWriterYou want to write text to a streamText data in chosen encodingBetter than BinaryWriter for text
BinaryReader.ReadString()You need to read strings written by BinaryWriterOriginal string restoredMust match the binary format

BinaryWriter vs StreamWriter

FeatureBinaryWriterStreamWriter
Main purposeWrite binary valuesWrite text
Writes string metadataYesNo
Good for plain text outputUsually noYes
Must be read by matching readerOften yesNot necessarily

If your goal is plain text, StreamWriter or Encoding.GetBytes() is usually the better choice.

Take Quiz

Cheat Sheet

// String -> byte[]
byte[] bytes = Encoding.UTF8.GetBytes("hello");

// byte[] -> string
string text = Encoding.UTF8.GetString(bytes);

Rules to remember

  • A string is text.
  • A byte[] is raw binary data.
  • You need an encoding to convert between them.
  • The same encoding should be used in both directions.
  • BinaryWriter.Write(string) does not write plain text only.
  • If bytes came from a binary format, do not assume they can be decoded as readable text.

Good choices

  • Use Encoding.UTF8 for most text data.
  • Use StreamWriter for writing text to streams.
  • Use BinaryWriter only when you want structured binary output.

Common safe conversion

string text = bytes == null ? string.Empty : Encoding.UTF8.GetString(bytes);

Edge case

If the byte array contains non-text binary bytes, converting it with GetString() may produce unreadable or invalid output.

FAQ

How do I convert a byte array to a string in C#?

Use a text encoding:

string text = Encoding.UTF8.GetString(bytes);

This works only if the bytes represent text in UTF-8.

Why does BinaryWriter.Write(string) not give me plain text bytes?

Because it writes the string in a binary format that includes extra length information, not just the character bytes.

Can I decode any byte array with UTF-8?

You can try, but the result is only meaningful if the bytes were actually encoded as UTF-8 text.

What encoding should I use in C#?

UTF-8 is the most common and safest default for text unless you know the data uses a different encoding.

How do I combine multiple strings into one byte array as text?

Join the strings first, then encode them:

string combined = "value1,value2";
byte[] bytes = Encoding.UTF8.GetBytes(combined);

What should I use instead of BinaryWriter for text?

Use Encoding.UTF8.GetBytes() or StreamWriter if you want plain text output.

Can I recover strings written by BinaryWriter without BinaryReader?

Only if you manually parse the binary format correctly. In general, the safest approach is to read binary-written data with the matching binary reader.

Take Quiz

Mini Project

Description

Build a small C# utility that stores a message as UTF-8 bytes and converts it back to a readable string. This demonstrates the correct way to handle text data as bytes without confusing plain text encoding with binary serialization.

Goal

Create a program that encodes text into a byte array and then decodes it back into the original string using UTF-8.

Requirements

  • Ask the user for a line of text.
  • Convert the text to a byte[] using UTF-8.
  • Print the byte values.
  • Convert the byte array back to a string.
  • Print the decoded string to confirm it matches the original input.
Take Quiz

Keep learning

Related questions

View more