.NET:读/写二进制字符串

发布于 2024-09-27 06:08:48 字数 733 浏览 0 评论 0原文

编辑:不要回答;我自己找到了解决方案。

我有一些代码可以执行此操作:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

只是在用心讲痛 2024-10-04 06:08:50

尝试将 writer.Write(ip.Iso3166CountryCode) 更改为 writer.Write(UnicodeEncoding.Default.GetBytes(ip.Iso3166CountryCode)) ,应该可以! :)

Try changing writer.Write(ip.Iso3166CountryCode) to writer.Write(UnicodeEncoding.Default.GetBytes(ip.Iso3166CountryCode)), that should work! :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文