C# 来自 MemoryStream UTF8 编码的 StreamReader

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14856084/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:14:04  来源:igfitidea点击:

StreamReader from MemoryStream UTF8 Encoding

c#streamreadermemorystream

提问by flow

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.

我想在 MemoryStream 中打开一个 XML 文件(来自 zip 存档)并从这个流中创建一个 StreamReader 以将其放入 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 StreamReaderlike that :

如果我的 XML 文件是用 ANSI 编码的,它就可以完美运行。但是当我加载以 UTF8 编码的文件时,它失败了,即使我StreamReader像这样初始化:

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

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

我希望有人会有一个想法来解决我的问题。

回答by Yaakov Ellis

Try using:

尝试使用:

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

The third param is for detectEncodingFromByteOrderMarks(msdn)

第三个参数用于detectEncodingFromByteOrderMarksmsdn