Click here to Skip to main content
15,892,161 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
i want to search by id in text file written with binary writer and display the rest of the records in text boxes this is code is my search code but i get an IOException (The process cannot access the file 'D:\file.txt' because it is being used by another process)
my class has recordsize=35; & count=0;
This is the data saved in text file after binary writer (2 records )

00001 1111 1111 1111100002 11111 11111 11111

What I have tried:

private void button2_Click(object sender, EventArgs e)
   {

       BinaryReader br = new BinaryReader(File.Open("D:\\SortedFile.txt", FileMode.Open, FileAccess.Read));
           for(int i = 0; i <Class1.count; i++)
           {
               br.BaseStream.Seek(Class1.count, SeekOrigin.Begin);
               if (br.Read() == int.Parse(textBox2.Text))
               {
                   MessageBox.Show("found");

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


               }

               Class1.count += Class1.rec_size;

               br.Close();
           }

       }
Posted
Updated 29-Apr-17 2:11am
v2
Comments
Dave Kreskowiak 29-Apr-17 11:34am    
Why in the hell are you writing text files with a binary writer? Use a StreamWriter instead. That will treat the file as a text file and make your life a lot easier.

1 solution

The error message is pretty clear:
The process cannot access the file 'D:\file.txt' because it is being used by another process

The file is open somewhere else, and when it was opened, it was given what's called an "exclusive lock" (this is normal for a file opened for writing to prevent two processes trying to change the same file and wrecking it for each other). Until the lock is removed (normally by closing the file) it cannot be opened by any process, even for reading.

Since you say you wrote the file using a binary writer, the most likely thing is that you didn't close the stream correctly and that code is causing the lock. Check your writer code and close and dispose all streams when you are finished with them.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900