Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Need help on Binary Reader/Writer

Status
Not open for further replies.

DarkWorlds

Technical User
Jul 20, 2005
64
US
Well I am in a bit of an issue, and I need help asap. Everything is figured out, even doing testing and it works. But when i throw it into a for loop it just dies on me.

private void Read()
{
FileStream fs = File.OpenRead(FILE_NAME);
BinaryReader br = new BinaryReader(fs);
if(File.Exists(FILE_NAME)&&fs.Length>0)
{
for(int i=0;i<members.Length;i++)
{
members.Status = br.ReadInt32();
members.Name = br.ReadString();
members.Address = br.ReadString();
members.City = br.ReadString();
members.State = br.ReadString();
members.Zip = br.ReadString();
members.Phonenumber = br.ReadString();
members.Gender = br.ReadString();
}
br.Close();
fs.Close();
}
}

Its erroring out on this statment (only when the file exisits) with the following error.

An unhandled exception of type 'System.IO.EndOfStreamException' occurred in mscorlib.dll

Additional information: Unable to read beyond the end of the stream.


Thanks for looking at this, if you need the full source of the program so you may compile it, the link is below.

 
Well if i do the following, it works. But if I do it this way, it doesnt get all that possible data.

private void Read()
{
FileStream fs = File.OpenRead(FILE_NAME);
BinaryReader br = new BinaryReader(fs);
if(File.Exists(FILE_NAME)&&fs.Length>0)
{
//for(int i=0;i<members.Length;i++)
//{
int i = 1;
members.Status = br.ReadInt32();
members.Name = br.ReadString();
members.Address = br.ReadString();
members.City = br.ReadString();
members.State = br.ReadString();
members.Zip = br.ReadString();
members.Phonenumber = br.ReadString();
members.Gender = br.ReadString();
//}
br.Close();
fs.Close();
}
}
 
Your looping code is tying the size of a serialized member to the filesize. You can't really do this because the size in memory is often different from the size on disk.

Try writing a single int at the top of the file for your count, and when you go to read it back in, read that first so you know how many members to attempt to read.

Chip H.


____________________________________________________________________
Donate to Katrina relief:
If you want to get the best response to a question, please read FAQ222-2244 first
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top