2010-11-24 85 views
6

我想弄清楚我在做什么错在这里。我试图使用二进制阅读器来缓解从流中获取最初的四个字节到一个Int32值,告诉我剩余数据需要多长时间。C#BinaryReader.Read()获取垃圾开始

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)); 
} 

输出应该是输入,但我得到这个(请注意,从字符串的第一个字符更改为字符串)

(想象一下,这是一个非常非常长的字符串

有人可以向我解释我做错了什么?理想情况下,第二次读取将继续,直到总读取字节等于前四个字节的值。此代码只是一个简化,以显示我遇到的问题。流的位置似乎相反ect(4),但它几乎看起来像从2开始读取。

+0

MSDN,你想读它。 – jason 2010-11-24 00:13:01

+0

呵呵,谢谢......而我是。对我来说不幸的是,BinaryReader没有提及Writer存储字符串的额外数据而不是字符串;) – James 2010-11-24 00:28:06

回答

8

BinaryWriter.Write(String)将长度为前缀的字符串写入此流。 这意味着它首先将字符串的长度写入流,然后使用某种编码写入字符串。长度一次编码七位,不是32位整数。

如果要从流中读取数据,则应使用BinaryReader.ReadString,它从流中读取长度为前缀的字符串。