您可以将编码传递给StreamReader,例如:
编码
StreamReader sr = new StreamReader(input_stream, Encoding.UTF8)
然而,根据文档,默认情况下使用的是UTF8编码。
更新
以下内容读取“Jalapeño”正常:
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;
}
}
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);
}
string s = Encoding.UTF8.GetString(bytes);
Console.WriteLine(s);
据我所知,“ñ”字符在以UTF编码存储文本时表示为0xc391。当您只读取一个字节时,会丢失数据。建议将整个流读取为字节数组(第一个示例),然后进行编码。或者使用StreamReader来完成工作。
int c
实际上保存的是一个字符或者 -1 表示文件结束(EOF),对于非 ASCII 值,看起来你正在丢弃一半的值 并且 从根本上改变编码方式... - undefined