0
I have an application that has a form that when loaded performs the reading of
a text file, from the first line to the last, with StreamReader
. The problem is I can’t read this same file twice in a row. 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 closure of the instance. Ex. Instancia.Close()
. But doing a debugging check that before running the Close method the instance is with the message:
EndOfStream = 'srv.EndOfStream' gerou uma exceção do tipo System.ObjectDisposedException'.
I keep running it, and I close this form. When I load the form again, for the second consecutive time, when will run the While
the instance is already as the same error and the While
is closed indicating that already arrived at the end of the archive.
As can be the end of the file, if theoretically it was closed at the end of the first execution and when I load again the reading should start from the beginning without major problems.
Can you please give me an idea of what’s going on?.
Thank you.
Follows 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();
}
}
}
}
}
Without code it’s hard to understand what you might be doing wrong
– Jorge Costa
This may be related to how you are opening and closing Streamreader. The best thing to do is to put in the code you’re using.
– João Martins
I agree with colleagues. I will arrange the display of the code.
– Gilberto V. Gonçalves