C# 如何将字节数组转换为字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11654562/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 18:41:20  来源:igfitidea点击:

How to convert byte array to string

c#arraysbinaryreader

提问by Oksana

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 resultto a string. I could do it using BinaryReader, but I cannot use BinaryReader(it is not supported).

我想转换result为字符串。我可以使用BinaryReader,但我不能使用BinaryReader(它不受支持)。

采纳答案by eulerfx

Depending on the encoding you wish to use:

根据您希望使用的编码:

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

回答by ba0708

Assuming that you are using UTF-8 encoding:

假设您使用的是 UTF-8 编码:

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);

回答by HforHisham

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

您可以使用BlockCopy在不处理编码的情况下做到这一点

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

回答by Mansoor Ali

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

要将 byte[] 转换为 string[],只需使用以下行。

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);