我怎么知道流已经结束?
我正在使用序列化来写入“将一些联系人及其姓名和电话添加到文件中”,我通过将每个联系人附加到文件中来单独写入每个联系人。
我想从文件中读取这些联系人并将它们放入 ListView 中。
Stream stream = File.Open("Contacts.dat", FileMode.Open);
BinaryFormatter BFormatter = new BinaryFormatter();
Contacts contact = (Contacts)BFormatter.Deserialize(stream);
listView1.Items.Add(new ListViewItem(new string[] { "", contact.name, contact.phone }));
执行上述代码后,我只得到一个联系人,如果我再次反序列化流,我会得到下一个联系人
Contacts contact2 = (Contacts)BFormatter.Deserialize(stream);
listView1.Items.Add(new ListViewItem(new string[] { "", contact2.name, contact2.phone}));
如何读取所有联系人? 或者我怎么知道流已经结束?
I am using serialization to write with Append some contacts with their name and phone to a file, I am writing each contact alone by append it to the file.
I want to read these contacts from the file and put them in a ListView.
Stream stream = File.Open("Contacts.dat", FileMode.Open);
BinaryFormatter BFormatter = new BinaryFormatter();
Contacts contact = (Contacts)BFormatter.Deserialize(stream);
listView1.Items.Add(new ListViewItem(new string[] { "", contact.name, contact.phone }));
After I am doing the above code I get only one contact and if I deserialize the stream again i get the next contact
Contacts contact2 = (Contacts)BFormatter.Deserialize(stream);
listView1.Items.Add(new ListViewItem(new string[] { "", contact2.name, contact2.phone}));
How can I read all the contacts?
or how can I know that the stream is end?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以根据流
Length
属性检查流Position
属性,假设您引用的是文件流You can check the stream
Position
property against streamLength
property, assuming your are refering to file stream这取决于它是哪种流。例如,
NetworkStream
永远不会结束(因为 TCP 是基于流的)。当Read
返回 0 字节时,FileStream
将结束。It depends on which kind of stream it is. For instance, a
NetworkStream
will never end (since TCP is stream based). AFileStream
will end whenRead
returns 0 bytes.