StreamReader from MemoryStream UTF8 Encoding

flow picture flow · Feb 13, 2013 · Viewed 37.9k times · Source

I want to open a XML file (from an zip archive) in a MemoryStream and create a StreamReader form this stream to put it into a GridView.

I use this code :

MemoryStream ms = new MemoryStream();
entry.Extract(ms);
StreamReader reader = new StreamReader(ms);
DataSet ds = new DataSet();
ds.ReadXml(reader);
dataGridView1.DataSource = GlobalDs.Tables[0];

If my XML files are encoded in ANSI, it works perfectly. But when I load files encoded in UTF8, it fail, even I initialize the StreamReader like that :

StreamReader reader = new StreamReader(ms, System.Text.Encoding.UTF8);

I hope someone will have an idea to solve my problem.

Answer

Yaakov Ellis picture Yaakov Ellis · Feb 13, 2013

Try using:

StreamReader reader = new StreamReader(ms, System.Text.Encoding.UTF8, true);

The third param is for detectEncodingFromByteOrderMarks (msdn)