[英]C# FileStream read set encoding
我在这里可能遗漏了一些明显的东西,但我似乎无法在我的 FileStream 读取中设置编码。 这是代码:
FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read);
using (fs)
{
byte[] buffer = new byte[chunk];
fs.Seek(chunk, SeekOrigin.Begin);
int bytesRead = fs.Read(buffer, 0, chunk);
while (bytesRead > 0)
{
ProcessChunk(buffer, bytesRead, database, id);
bytesRead = fs.Read(buffer, 0, chunk);
}
}
fs.Close();
ProcessChunk 将读取的值保存到对象,然后将其序列化为 XML,但读取的字符显示错误。 编码需要是 1250。我还没有看到将编码添加到 FileStream 的选项。 我在这里缺少什么?
使用 StreamReader 而不是 FileStream。 它有几个构造函数,允许您指定编码。 例如:
StreamReader sr = new StreamReader(file, System.Text.Encoding.ASCII);
由于您需要编码 1250,因此可以通过以下方式完成:
StreamReader sr = new StreamReader(file, System.Text.Encoding.GetEncoding(1250));
我还建议将其写为:
using (StreamReader sr = new StreamReader ...etc)
而不是在 using 之外声明变量; 并且您不需要在 using 之外执行 Close,因为Dispose 将处理那个。
您还可以同时使用 FileStream 和 FileReader :
using (FileStream fs = new FileStream(_fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (StreamReader sr = new StreamReader(fs, Encoding.GetEncoding(1252)))
{
while (!sr.EndOfStream)
ProcessLine(sr.ReadLine());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.