2

我有一个从流中读取字符串数据的应用程序。字符串数据通常是英文的,但有时它会遇到像“Jalapeño”这样的东西,而“ñ”则显示为“?”。在我的实现中,我更喜欢将流内容读入字节数组,但我可以通过将内容读入字符串来获得。知道我能做些什么来使这项工作正确吗?

当前代码如下:

byte[] data = new byte[len];  // len is known a priori
byte[] temp = new byte[2];
StreamReader sr = new StreamReader(input_stream);
int position = 0;
while (!sr.EndOfStream)
{
  int c = sr.Read();
  temp = System.BitConverter.GetBytes(c);
  data[position] = temp[0];
  position++;
}
input_stream.Close();
sr.Close();
4

2 回答 2

4

您可以将编码传递给 StreamReader,如下所示:

StreamReader sr = new StreamReader(input_stream, Encoding.UTF8);

但是,我知道根据文档默认使用 Encoding.UTF8 。

更新

下面的“墨西哥胡椒”很好:

byte[] bytes;
using (var stream = new FileStream("input.txt", FileMode.Open, FileAccess.Read, FileShare.Read))
{
    var index = 0;
    var count = (int) stream.Length;
    bytes = new byte[count];
    while (count > 0)
    {
        int n = stream.Read(bytes, index, count);
        if (n == 0)
            throw new EndOfStreamException();

        index += n;
        count -= n;
    }
}

// test
string s = Encoding.UTF8.GetString(bytes);
Console.WriteLine(s);

就像这样:

byte[] bytes;
using (var stream = new FileStream("input.txt", FileMode.Open, FileAccess.Read, FileShare.Read))
{
    var reader = new StreamReader(stream);
    string text = reader.ReadToEnd();
    bytes = Encoding.UTF8.GetBytes(text);
}

// test
string s = Encoding.UTF8.GetString(bytes);
Console.WriteLine(s);

据我了解,当文本以 UTF 编码存储时,文本中的“ñ”字符表示为 0xc391。当您只读取一个字节时,您将丢失数据。

我建议将整个流作为字节数组读取(第一个示例),然后进行编码。或使用 StreamReader 为您完成工作。

于 2012-10-27T05:29:58.587 回答
1

由于您正在尝试将内容填充到字节数组中,因此请不要打扰阅读器 - 它对您没有帮助。仅使用流:

byte[] data = new byte[len];
int read, offset = 0;
while(len > 0 &&
    (read = input_stream.Read(data, offset, len)) > 0)
{
    len -= read;
    offset += read;
}
if(len != 0) throw new EndOfStreamException();
于 2012-10-27T07:26:03.593 回答