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

viv*_*ain 2 c# bytearray

作为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;
Run Code Online (Sandbox Code Playgroud)

我想"你好"应该是'strFinalFileContent'的值.我得到"104 101 108 108 111"表示ASCII字符的十进制值.请帮助我如何获得"地狱o"作为输出.这可能是我的小问题,但我是初学者所以请帮助我.

Jon*_*eet 6

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

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

另请注意,此行很危险:

myStream.Read(Input, 0, fileLen);
Run Code Online (Sandbox Code Playgroud)

假设这一个Read调用将读取所有数据.一般来说,对于流不是这样.您应该始终使用Stream.Read(或TextReader.Read)的返回值来查看您实际阅读的数量.

在实践中,使用a 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();
}
Run Code Online (Sandbox Code Playgroud)