C# 中的字节数组到字符串

本文关键字:数组 字符串 字节数 字节 | 更新日期: 2023-09-27 18:31:43

因为我是C#的新手,我遇到了一个非常基本的问题。

我正在读取一个文本文件,其中包含一些数据(例如"hello")我正在像下面提到的代码一样读取这些数据。

System.IO.Stream myStream;
Int32 fileLen;
StringBuilder displayString = new StringBuilder();
// Get the length of the file.
fileLen = FileUploadId.PostedFile.ContentLength;
// Display the length of the file in a label.
string strLengthOfFileInByte = "The length of the file is " +
fileLen.ToString() + " bytes.";
// Create a byte array to hold the contents of the file.
Byte[] Input = new Byte[fileLen];
// Initialize the stream to read the uploaded file.
myStream = FileUploadId.FileContent;
// Read the file into the byte array.
//myStream.Read(Input, 0, fileLen);
myStream.Read(Input, 0, fileLen);
// Copy the byte array to a string.
for (int loop1 = 0; loop1 < fileLen; loop1++)
{
    displayString.Append(Input[loop1].ToString());
}
// Display the contents of the file in a 
string strFinalFileContent = displayString.ToString();
return strFinalFileContent;

我希望"hello"应该是"strFinalFileContent"的值。我得到"104 101 108 108 111"表示 ASCII 字符的十进制值。请帮助我如何获取"h e l l o"作为输出。这可能是我的小问题,但我是初学者,所以请帮助我。

C# 中的字节数组到字符串

应使用 Encoding 对象指定要用于将二进制数据转换为文本的编码。从你的帖子中不清楚输入文件实际上是什么,或者你是否会提前知道编码 - 但如果你知道的话,它会简单得多

我建议您使用给定的编码创建一个StreamReader,包装您的流 - 并从中读取文本。否则,如果字符被拆分为二进制读取,您可能会在阅读"半个字符"时遇到有趣的困难。

另请注意,此行很危险:

myStream.Read(Input, 0, fileLen);

假设这一次Read调用将读取所有数据。一般来说,对于流来说并非如此。您应该始终使用 Stream.Read(或TextReader.Read)的返回值来查看您实际读取了多少内容。

实际上,使用StreamReader将使所有这些变得更加简单。您的整个代码可以替换为:

// Replace Encoding.UTF8 with whichever encoding you're interested in. If you
// don't specify an encoding at all, it will default to UTF-8.
using (var reader = new StreamReader(FileUploadId.FileContent, Encoding.UTF8))
{
    return reader.ReadToEnd();
}

将所有文本读入字符串变量

string fileContent;
using(StreamReader sr = new StreamReader("Your file path here")){
    sr.ReadToEnd();
}
如果需要特定的

编码,请不要忘记使用新 StreamReader 的重载。流阅读器文档

然后在每个字符之间添加一个空格(这个要求对我来说很奇怪,但如果你真的想......

string withSpaces = string.Concat(fileContent.ToCharArray().Select(n=>n + " ").ToArray());

这将采用每个字符,将其拆分为一个数组,使用 linq 为每个字符添加额外的空格,然后将结果连接成一个连接的字符串。

我希望这能解决你的问题!

string displayString = System.Text.Encoding.UTF8.GetString(Input);