C#FileStream读取集编码 [英] C# FileStream read set encoding

查看:661
本文介绍了C#FileStream读取集编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里可能缺少一些明显的东西,但是我似乎无法在读取的FileStream上设置编码。代码如下:

There might be something obvious I'm missing here, but I can't seem to set the encoding on my FileStream read. Here's the code:

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的选项。我在这里缺少什么?

Where ProcessChunk saves the read values to objects which are then serialized to XML, but the characters read appear wrong. The encoding needs to be 1250. I haven't seen an option to add the encoding to the FileStream. What am I missing here?

推荐答案

使用StreamReader而不是FileStream。它具有几个构造函数,可让您指定编码。例如:

Rather than FileStream, use StreamReader. It has several constructors which allow you to specify the Encoding. For example:

StreamReader sr = new StreamReader(file, System.Text.Encoding.ASCII);

由于您需要编码1250,因此可以通过以下方式完成:

Since you require encoding 1250, this can be done with:

StreamReader sr = new StreamReader(file, System.Text.Encoding.GetEncoding(1250));

我也建议将其写为:

using (StreamReader sr = new StreamReader ...etc)

而不是在using之外声明变量;而且您无需在使用之外执行关闭操作,因为则由Dispose处理。

rather than declaring the variable outside the using; and you don't need to do the Close outside the using, since the Dispose will handle that.

这篇关于C#FileStream读取集编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆