I have an application that has a form that when loaded reads
a text file, from the first line to the last one, with StreamReader
. The problem is that I can not read this file for 2 consecutive times. The only way to read the file again is to close the entire system and start again. In the first reading, at the end I execute the closing of the instance. Ex. Instancia.Close()
. But doing a debugging check that before executing the Close method the instance is with the message:
EndOfStream = 'srv.EndOfStream' gerou uma exceção do tipo System.ObjectDisposedException'.
I keep running, and I close this form. When I reload the form, for the second consecutive time, when it will execute While
the instance is already the same error and While
is exited indicating that it has reached the end of the file.
How can it be the end of the file, if theoretically it was closed at the end of the first execution and when I load the reading again should start at the beginning without major problems.
Can you please give me an idea of what happens?
Thank you.
Follow the code:
namespace TesteStreamReaderACBRSAT
{
public partial class LeituraArquivo : Form
{
static string linha;
static string ArquivoVendaIni = "C:\SAT\VENDA.INI";
static string ArquivoEntrada = @"C:\SAT\ENT.TXT";
static StreamReader srv = new StreamReader(ArquivoVendaIni);
static StreamWriter swe = new StreamWriter(ArquivoEntrada, true);
public LeituraArquivo()
{
InitializeComponent();
}
private void LeituraArquivo_Load(object sender, EventArgs e)
{
LerArquivo();
}
public static void LerArquivo()
{
if (File.Exists(ArquivoVendaIni))
{
try
{
while ((linha = srv.ReadLine()) != null)
{
VerQualEmpresa();
GravarArquivo();
}
swe.Close();
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message);
}
}
else
{
//MessageBox.Show(" O arquivo " + arquivo + " não foi localizado");
}
}
private static void GravarArquivo()
{
swe.WriteLine(linha);
}
private static void VerQualEmpresa()
{
if (true) // Aqui se uma determinada condição for verdadeira deve-se ler algumas
// linhas do arquivo e depois a leitura continua no método LeituraArquivo()
{
while ((linha = srv.ReadLine()) != null)
{
GravarArquivo();
}
}
}
}
}