Flopn
Flopn

Reputation: 195

C# FileStream read set encoding

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?

Upvotes: 1

Views: 16620

Answers (2)

Elo
Elo

Reputation: 2352

You can also use both FileStream and 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());
    }
}

Upvotes: 3

Richardissimo
Richardissimo

Reputation: 5763

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

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

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

I would also suggest writing it as:

using (StreamReader sr = 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.

Upvotes: 7

Related Questions