C# FileStream read set encoding

人盡茶涼 提交于 2020-03-05 09:35:10

问题


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();

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?


回答1:


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

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

I would also suggest writing it as:

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

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.



来源:https://stackoverflow.com/questions/40791109/c-sharp-filestream-read-set-encoding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!