Reputation: 33
i am trying to search within a text file written with BinaryWriter
and have to input the id
i want to search in TextBox
and then search for it But the problem is that i have to enter the same order of id to search for
for example suppose that i have 3 records with id 1,2,3
if i enter 1 it will show it's data in text box
then if i enter 3 it will show it's data in text box
but when i enter 2 it will show the exception (Unable to read beyond the end of the stream
)
This is my code to search in text file and display the rest of data in text boxes in form (Record Size = 35)
BinaryReader br = new BinaryReader(File.Open("D:\\File.txt",
FileMode.Open, FileAccess.Read));
int num_records = (int)br.BaseStream.Length / Class1.rec_size;
int x = int.Parse(textBox2.Text);
for (int i = 0; i < num_records; i++)
{
br.BaseStream.Seek(Class1.count, SeekOrigin.Begin);
if (int.Parse(br.ReadString()) == x)
{
// textBox2.Text = int.Parse(br.ReadString()).ToString();
textBox3.Text = br.ReadString();
textBox4.Text = br.ReadString();
textBox5.Text = int.Parse(br.ReadString()).ToString();
textBox6.Text = br.ReadString();
break;
}
Class1.count += Class1.rec_size;
}
br.Close();
}
Upvotes: 3
Views: 102
Reputation: 2659
It seems that you forget to reset your Class1.Count.
In your codeline:
br.BaseStream.Seek(Class1.count, SeekOrigin.Begin);
You have an offset of Class1.Count. Since at the end of each record you add to the offset Class1.count += Class1.rec_size;
you will only search the stream in upward direction, that is why it succeeds in an ordered search.
You need to reset this counter for each search to start at the beginning of the stream again.
Upvotes: 1