C# Lectura línea por línea del archivo al cuadro de lista
Frecuentes
Visto 2,400 veces
0
I have a problem with reading text from file line by line.
System.IO.StreamReader file = new System.IO.StreamReader("ais.txt");
while ((line = file.ReadLine()) != null)
{
listBox1.Items.Add(line);
}
This code only read last line from file and display in listbox. How can I read line-by-line?
For example: read a line, wait 1 second, read another line, wait 1 second...ect.?
4 Respuestas
1
If you want to read lines one at a time with a one second delay, you can add a timer to your form to do this (set it to 1000):
System.IO.StreamReader file = new System.IO.StreamReader("ais.txt");
String line;
private void timer1_Tick(object sender, EventArgs e)
{
if ((line = file.ReadLine()) != null)
{
listBox1.Items.Add(line);
}
else
{
timer1.Enabled = false;
file.Close();
}
}
You could also read the lines all at once and simply display them one at a time, but I was trying to keep this as close to your code as possible.
Respondido el 28 de enero de 14 a las 18:01
It's quite important to close the reader when you're done with it. - Servir
1
await
makes this very easy. We can just loop through all of the lines and await Task.Delay
to asynchronously wait for a period of time before continuing, while still not blocking the UI thread.
public async Task DisplayLinesSlowly()
{
foreach (var line in File.ReadLines("ais.txt"))
{
listBox1.Items.Add(line);
await Task.Delay(1000);
}
}
Respondido el 28 de enero de 14 a las 18:01
0
¿Has probado Archivo.ReadAllLines? You can do something like this:
string[] lines = File.ReadAllLines(path);
foreach(string line in lines)
{
listBox1.Items.Add(line);
}
Respondido el 28 de enero de 14 a las 18:01
0
You can read all lines and save to array string
string[] file_lines = File.ReadAllLines("ais.txt");
and then read line by line by button click or use timer to wait 1 second
Respondido el 28 de enero de 14 a las 18:01
No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas c# readline line-by-line or haz tu propia pregunta.
Have you tried File.ReadAllLines () function? - thomas
I understand reading each line, but are these 1 second waits important? Why not just read in all the lines? - Jon B
Incidentally, other than not declaring
line
, your code works fine. - Jon B@JonB is correct...what exactly is the problem? - DonBoitnott
" wait 1 second," Why on earth would you want to do that? - Steve Wellens