访问文件 C# 时出错

Error while accessing file C#

我收到错误 (IOException),我不知道错误在哪里。他在这里代码:

构造函数:

 private const int MAX = 200;
    private String path = "\Registros\reg";
    private FileStream fs;
    private BinaryWriter bw = null;
    private BinaryReader br = null;
    private int N;
    private long pos;

 public Manejo_Ficheros(String filepath){
    this.path = filepath;
        if(!File.Exists(path+".dat")){
            fs = new FileStream(path + ".dat", FileMode.Create);
            this.N = 0;
            bw = new BinaryWriter(fs);
            fs.Seek(0,SeekOrigin.Begin);
            bw.Write(N);
        }else{
            fs = new FileStream(path + ".dat", FileMode.Open);
            br = new BinaryReader(fs);
            fs.Seek(0,SeekOrigin.Begin);
            this.N = br.ReadInt32();    
        }
}

这里是写作:

public void escribirRegistro(Persona p)
    {
        pos = 4 + this.N * MAX;
        int i = (int)pos;
        bw = new BinaryWriter(fs);
        bw.Seek(i, SeekOrigin.Begin);
        bw.Write(p.ID);
        bw.Write(p.nombre);
        bw.Write(p.apellidos);
        bw.Write(p.Num);
        bw.Write(p.Nced);
        bw.Write(p.pais);
        bw.Write(p.observaciones);
        bw.Write(p.Anac);
        bw.Write(p.tPer);
        this.N += 1;
        fs.Seek(0, SeekOrigin.Begin);
        bw.Write(N);
        bw.Close();

        fs.Close();
    }

如您所见,我正在使用同花顺。它将接收一个 "Persona" 对象类型,然后写入一个文件。

写作工作正常。但是当我想使用阅读方法时,请参阅:

    public Persona[] leerTodos()
    {
        Persona[] p = new Persona[this.N];
        br = new BinaryReader(fs);
        for (int i = 0; i < p.Length; i++)
        {
            pos = 4+i*MAX;
            br.BaseStream.Seek(pos, SeekOrigin.Begin);

            Persona p1 = new Persona();
            p1.ID = br.ReadInt32();
            p1.nombre = br.ReadString();
            p1.apellidos = br.ReadString();
            p1.Num = br.ReadString();
            p1.Nced = br.ReadString();
            p1.pais = br.ReadString();
            p1.observaciones = br.ReadString();
            p1.Anac = br.ReadInt32();
            p1.tPer = br.ReadString();
            p[i] = p1;
        }
        return p;
    }

应用程序在此行中断fs = new FileStream(path + ".dat", FileMode.Open);进程无法访问文件'C:\Users\Allan\Desktop\data.dat',因为它正被另一个进程使用。

写它的事情不会发生。我不知道出了什么问题。

尝试在您的代码中这样做

 public Manejo_Ficheros(String filepath){
  this.path = filepath;
    if(!File.Exists(path+".dat")){
        using (fs = new FileStream(path + ".dat", FileMode.Create));
        {
          this.N = 0;
          bw = new BinaryWriter(fs);
          fs.Seek(0,SeekOrigin.Begin);
          bw.Write(N);
        }
    }else{
        using (fs = new FileStream(path + ".dat", FileMode.Open))
        {
          br = new BinaryReader(fs);
          fs.Seek(0,SeekOrigin.Begin);
          this.N = br.ReadInt32();
        }    
    }