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:
-
The byte array contains plain text bytes
Use an encoding likeEncoding.UTF8.GetString(bytes). -
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.
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?
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.
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:
"cat"is a C# string.Encoding.UTF8.GetBytes("cat")converts each character into UTF-8 bytes.- The byte array now contains the raw byte values for
c,a, andt. Encoding.UTF8.GetString(bytes)reads those bytes using the same UTF-8 rules.- 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();
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.
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 ()
{
(bytes == || bytes.Length == )
.Empty;
Encoding.UTF8.GetString(bytes);
}
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);
Comparisons
| Approach | Use when | Result | Notes |
|---|---|---|---|
Encoding.UTF8.GetString(bytes) | Bytes are plain UTF-8 text | Readable string | Best for text data |
Encoding.UTF8.GetBytes(text) | You want text as bytes | byte[] | Reverse operation |
BinaryWriter.Write(string) | You want to store strings in a binary format | Structured binary data | Includes length metadata |
StreamWriter | You want to write text to a stream | Text data in chosen encoding | Better than BinaryWriter for text |
Cheat Sheet
// String -> byte[]
byte[] bytes = Encoding.UTF8.GetBytes("hello");
// byte[] -> string
string text = Encoding.UTF8.GetString(bytes);
Rules to remember
- A
stringis 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.UTF8for most text data. - Use
StreamWriterfor writing text to streams. - Use
BinaryWriteronly 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 ?
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.
Keep learning
Related questions
AddTransient vs AddScoped vs AddSingleton in ASP.NET Core Dependency Injection
Learn the differences between AddTransient, AddScoped, and AddSingleton in ASP.NET Core DI with examples and practical usage.
Best Way to Repeat a Character in C#: Building Repeated Strings Efficiently
Learn the best way to repeat a character in C#, compare StringBuilder, string concatenation, and simpler built-in options.
C# Array Initialization Syntaxes Explained
Learn all common C# array initialization syntaxes with examples, rules, comparisons, and mistakes beginners often make.