No need for BinaryReader in C# to convert byte array to string
When manipulating data in a byte array, it is often necessary to convert it to a string for further processing or display. This article explores how to perform this conversion using C# without relying on the BinaryReader class.
Question:
You have created a byte array containing one or more strings and need to retrieve the string value from the byte array. However, due to compatibility restrictions, the BinaryReader class cannot be used.
Solution:
To convert a byte array to a string, you can use the System.Text.Encoding.Default.GetString() method. This method takes a byte array as input and automatically determines the appropriate encoding based on the system's default settings.
<code class="language-csharp">byte[] result = reader.ReadBytes((int)binWriter.BaseStream.Length); var str = System.Text.Encoding.Default.GetString(result);</code>
However, it is important to note that the default encoding may not always suit your specific needs. In this case, you can explicitly specify the desired encoding using one of the following methods:
<code class="language-csharp">// 使用 ASCII 编码转换 var str = System.Text.Encoding.ASCII.GetString(result); // 使用 UTF-8 编码转换 var str = System.Text.Encoding.UTF8.GetString(result); //等等</code>
The above is the detailed content of How to Convert Byte Arrays to Strings in C# Without Using BinaryReader?. For more information, please follow other related articles on the PHP Chinese website!