I have a class that retrieves data from bank and saves in a D.Reader, and I write each record in a text file, in this method:
public void Escreve_Arquivos_Txt()
{
string folder = Program.caminhoAplicacao + @"\Serializer"; //Cria Pasta para Serialização
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
int ContaArquivo = 0;
int count = dataReader.FieldCount;
using (file = new StreamWriter(Program.caminhoAplicacao + @"\Serializer\" + ContaArquivo + "Ser.txt"))
{
while (this.dataReader.Read())
{
file.AutoFlush = true; // Limpa o buffer pra forçar a escrita
for (int i = 0; i < count; i++)
{
file.WriteLine(this.dataReader.GetValue(i));
}
ContaArquivo++;
file = new StreamWriter(Program.caminhoAplicacao + @"\Serializer\" + ContaArquivo + @"Ser.txt");
}
}
file.Dispose();
}
And I have another method to read these files, insert into a d.table and delete what is being read, in that other method:
private DataTable Preenche_Datatable(DataTable dataTable, int ContaArquivo, string diretorio, int quant_coluna)
{
do
{
int auxiliacount = quant_coluna - 1;
int colunaIndex = 0;
string[] totaldelinhas = File.ReadAllLines(diretorio + ContaArquivo + "Ser.txt");
DataRow dr = dataTable.NewRow();
foreach (string contalinhas in totaldelinhas)
{
dr[colunaIndex] = contalinhas;
if (colunaIndex == auxiliacount)
{
dataTable.Rows.Add(dr);
dr = dataTable.NewRow();
colunaIndex = 0;
}
else
{
colunaIndex++;
}
}
File.Delete(diretorio + ContaArquivo + "Ser.txt");
ContaArquivo++;
}
while (File.Exists(diretorio + ContaArquivo + "Ser.txt"));
return dataTable;
}
Let's get into the problem ... It writes everything quietly ... At the time of reading, randomly, some files are not closed and throw the exception of System.IO ( question title ) in that line:
string[] totaldelinhas = File.ReadAllLines(diretorio + ContaArquivo + "Ser.txt");
I've tried using Lock, synchronized, GC dispose to try to isolate the thread / process and I did not succeed. It is worth mentioning that if I execute the 2 methods separately, 1st I execute the program to write closing and then I open to read, it does not throw this exception. And I also did the reading, skipping those that were being used and it is not a cascade (cascade in the sense of "that file forward"), are random files that are still being "used" ... I already used Close and Dispose individually and together in the first method.
Here's the calling method if needed:
public DataTable Nova_Serializacao(DataTable dataTable)
{
Escreve_Arquivos_Txt();
string dir = Program.caminhoAplicacao + @"\Serializer\";
int count = dataReader.FieldCount;
Recupera_Colunas(dataReader, count);
int ContaArquivo = 0;
Preenche_Datatable(dataTable, ContaArquivo, dir, count);
return dataTable;
}
Does anyone have an idea what it might be?