如何在C#中搜索用二进制写入器编写的文本文件? [英] How do I search in text file written with binary writer in C#?

查看:82
本文介绍了如何在C#中搜索用二进制写入器编写的文本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在用二进制编写器编写的文本文件中通过id搜索并在文本框中显示其余记录这是代码是我的搜索代码但是我得到一个IOException(该进程无法访问文件'D:\ file.txt'因为它正在被另一个进程使用)

我的类有recordize = 35; &安培; count = 0;

这是二进制写入后保存在文本文件中的数据(2条记录)



?00001 1111?1111?1111 ?1?00002 11111?11111?1111?1



我的尝试:



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

       }

推荐答案

错误信息非常清楚:

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.


这篇关于如何在C#中搜索用二进制写入器编写的文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆