Searching in a text file in C #?

I am trying to search a text file written with BinaryWriter

and must typeid

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 example , suppose I have 3 records with id 1,2,3 if I enter 1 it will show the data in the textbox then if I enter in 3, it will display it in the textbox but when I enter 2 it will show an exception ( Unable to read beyond the end of the stream

)

This is my code for searching a text file and displaying the rest of the data in text fields in a 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();
    }

      

+3


source to share


1 answer


It seems like you forgot to reset your Class1.Count.

In your encoding:        br.BaseStream.Seek(Class1.count, SeekOrigin.Begin);

You have an offset of Class1.Count. Since at the end of each entry you add to offset Class1.count += Class1.rec_size;

, you will only search the stream in the upward direction, so it will succeed in doing an ordered search.



You need to reset this counter so that each search starts from the beginning of the stream again.

+1


source







All Articles