Allan Ramirez Allan Ramirez - 20 days ago 7
C# Question

Error while accessing file C#

I get the Error (IOException) that I don't know where is the error. Here he code:

The constructor:

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


Here the Writting:

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


As you can see, I am using a flush. It will receive a "Persona" object type and then Writting to a File.

The writting is working fine. But when I want to use the reading method see:

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


The application breaks in this line
fs = new FileStream(path + ".dat", FileMode.Open);
The process cannot access the file 'C:\Users\Allan\Desktop\data.dat' because it is being used by another process.

Thing that Writting it does not happen. I dont know what is going wrong.

Answer

Try doing this in your code

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