C# 使用前导码或默认编码将字节数组转换为字符串
我正在尝试将字节数组转换为字符串。字节数组包含一个前导码(如果使用的编码器有其中之一),如果字节数组中没有存储前导码,则必须指定默认编码。
我的代码看起来像这样,
public static string ArrayToStringUsingPreambleOrDefaultEncoder(byte[] bytes, Encoding defaultEncoder, out Encoding usedEncoder) {
using (var mem = new MemoryStream(bytes))
using (var reader = new StreamReader(mem, defaultEncoder, true)) {
string result = reader.ReadToEnd();
usedEncoder = reader.CurrentEncoding;
return result;
}
}
但它并没有达到我预期的效果。 如何使 StreamReader 使用前导码指定的编码或如果未找到前导码则使用默认编码。我真的需要手动将所有已知编码器的前导码与数组的开头进行比较才能找到正确的编码器吗?
Im trying to convert a byte array to a string. The byte array includes a preamble (if the used encoder had one of those), and you must specify the default encoding if no preamble is stored in the byte array.
My code looks like this
public static string ArrayToStringUsingPreambleOrDefaultEncoder(byte[] bytes, Encoding defaultEncoder, out Encoding usedEncoder) {
using (var mem = new MemoryStream(bytes))
using (var reader = new StreamReader(mem, defaultEncoder, true)) {
string result = reader.ReadToEnd();
usedEncoder = reader.CurrentEncoding;
return result;
}
}
But it doesnt do the trick as I would expect.
How do I make a StreamReader use the encoding specified by the preamble or a default encoding if no preamble is found. Do I really have to manually compare the preamble of ALL known encoders to the start of the array to find the right one?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
来自 MSDN:“StreamReader 专为字符输入而设计在特定的编码中”。所以,是的,您确实需要从前导码中嗅出正确的编码才能做到这一点。这里有一个示例方法:
http://www .personalmicrocosms.com/Pages/dotnettips.aspx?c=15&t=17
编辑:上述链接已损坏,但旧页面可在 Wayback Machine Internet Archive 中找到:https: //web.archive.org/web/20090203034127/http://www.personalmicrocosms.com/Pages/dotnettips.aspx?c=15&t=17*
From MSDN: "StreamReader is designed for character input in a particular encoding". So yes, you really do need to sniff out the correct encoding from the preamble to do this. There's an example method to do this here:
http://www.personalmicrocosms.com/Pages/dotnettips.aspx?c=15&t=17
Edit: The above link is broken but the old page is available at Wayback Machine Internet Archive: https://web.archive.org/web/20090203034127/http://www.personalmicrocosms.com/Pages/dotnettips.aspx?c=15&t=17*