我得到错误(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”,因为它正由另一个进程使用。
写它不会发生的事情。我不知道出了什么问题。
答案 0 :(得分:1)
尝试在您的代码中执行此操作
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();
}
}