问题
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