简体   繁体   English

C#BinaryReader.Read()以垃圾开头

[英]C# BinaryReader.Read() gets junk to start with

I am trying to figure out what I am doing wrong here. 我试图找出我在这里做错了什么。 I am attempting to use a Binary Reader to ease getting an initial four bytes from a stream into an Int32 value that tells me how long the rest of the data is to be expected. 我正在尝试使用二进制读取器来简化从流中获取初始四个字节到Int32值,该值告诉我其余数据的预期时间。

static void Main(string[] args)
{
    MemoryStream stream = new MemoryStream();

    BinaryWriter writer = new BinaryWriter(stream);

    string s = "Imagine this is a very very long string.";

    writer.Write(s.Length);
    writer.Write(s);
    writer.Flush();

    BinaryReader reader = new BinaryReader(stream);
    reader.BaseStream.Seek(0, SeekOrigin.Begin);

    char[] aChars = new char[reader.ReadInt32()];
    reader.Read(aChars, 0, aChars.Length);
    Console.WriteLine(new string(aChars));
}

The output should be the input, but I get this (Note that the first character changes from string to string) 输出应该是输入,但我得到这个(注意第一个字符从字符串更改为字符串)

(Imagine this is a very very long string (想象一下,这是一个非常长的字符串

Can someone explain to me what I am doing wrong? 有人可以向我解释我做错了什么吗? Ideally the second read would continue until the total read bytes was equal to the value of the first four bytes.. this code is just a simplification to show the problem I am running into. 理想情况下,第二次读取将继续,直到总读取字节数等于前四个字节的值。此代码只是一个简化,以显示我遇到的问题。 The position of the stream seems correct (4) but it almost seems like it starts reading at 2. 流的位置似乎是正确的(4)但它几乎看起来像是从2开始读取。

BinaryWriter.Write(String) writes a length-prefixed string to this stream. BinaryWriter.Write(String)将长度为前缀的字符串写入此流。 This means it first writes the length of the string to the stream, and then the string using some encoding. 这意味着它首先将字符串的长度写入流,然后使用某种编码将字符串写入字符串。 The length is encoded seven bits at a time, not as 32-bit integer. 长度一次编码7位,而不是32位整数。

If you want to read from the stream, you should use BinaryReader.ReadString , which reads a length-prefixed string from the stream. 如果要从流中读取,则应使用BinaryReader.ReadString ,它从流中读取长度为前缀的字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM