.NET: Reading/writing binary string
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.
Try changing writer.Write(ip.Iso3166CountryCode)
to writer.Write(UnicodeEncoding.Default.GetBytes(ip.Iso3166CountryCode))
, that should work! :)
精彩评论