.NET:读/写二进制字符串
编辑:不要回答;我自己找到了解决方案。
我有一些代码可以执行此操作:
using (var stream = new FileStream(args[1], FileMode.Create))
{
using (var writer = new BinaryWriter(stream))
{
writer.Write(ip.Iso3166CountryCode);
...
}
}
Iso3166CountryCode
是一个带有两个字符(“US”)的字符串
。
当我尝试从文件中读取“US”时:
// line is a byte[] from the file with the first 1024 bytes
UnicodeEncoding.Default.GetString(line.Take(2).ToArray());
我没有得到“US”,而是得到了一些奇怪的 ASCII 字符。如何从此二进制文件中读取两个国家/地区代码字符?
编辑:没关系。我将 writer.Write(ip.Iso3166CountryCode) 更改为 writer.Write(UnicodeEncoding.Default.GetBytes(ip.Iso3166CountryCode)) 并且它有效。 EM>
EDIT: Don't answer; I've found the solution on my own.
I have some code that does this:
using (var stream = new FileStream(args[1], FileMode.Create))
{
using (var writer = new BinaryWriter(stream))
{
writer.Write(ip.Iso3166CountryCode);
...
}
}
Iso3166CountryCode
is a string
with two characters ("US").
When I try to read "US" from the file:
// line is a byte[] from the file with the first 1024 bytes
UnicodeEncoding.Default.GetString(line.Take(2).ToArray());
I don't get "US" back, I get some odd ASCII characters back. How do I read the two country-code characters from this binary file?
EDIT: NEVER MIND. I changed writer.Write(ip.Iso3166CountryCode)
to writer.Write(UnicodeEncoding.Default.GetBytes(ip.Iso3166CountryCode))
and it works.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试将 writer.Write(ip.Iso3166CountryCode) 更改为 writer.Write(UnicodeEncoding.Default.GetBytes(ip.Iso3166CountryCode)) ,应该可以! :)
Try changing
writer.Write(ip.Iso3166CountryCode)
towriter.Write(UnicodeEncoding.Default.GetBytes(ip.Iso3166CountryCode))
, that should work! :)