Click here to Skip to main content
15,920,602 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hi
So what i am trying to do is to skip reading a specific number of lines when reading a textfile using stream reader.

This code i want to try an do is to load a text file and skip a specific number of lines and load it in a list box.

I have this code so far

C#
string[] allines = File.ReadLines(@"Root").Skip(3)

listbox.items.addrange(alllines);




but the skip bit does not work when loading the text file into a listbox as the lines still come up in the list box.

any suggestions and help please :)
Posted

You don't have any code in there to skip any lines, so it's loading all the lines into the ListBox.

You have to enumerate the collection of lines, one-by-one, and only add the lines to the ListBox that you want, depending on some condition you didn't specify.

The other benefit of loading one line at a time is that you're not crushing your memory loading an entire file into an array if the source file is huge.
 
Share this answer
 
v2
Comments
Sergey Alexandrovich Kryukov 13-May-13 12:56pm    
As simple as that, a 5.
—SA
Your issue, I believe relates to the fact that Skip uses defered execution.

(see remarks on the following link)
http://msdn.microsoft.com/en-us/library/bb358985(v=vs.90).aspx[^]

I would suggest breaking the code down a bit:

C#
IEnumerable<string> allines = File.ReadLines(@"Root");
IEnumerable<string> cutDown = alllines.Skip(3).GetEnumerator();
listbox.items.addrange(alllines);


Or you could do:

C#
IEnumerable<string> allines = File.ReadLines(@"Root");
IEnumerable<string> cutDown = alllines.Skip(3);

foreach( string s in cutDown)
{
    listbox.items.add(s);
}
 
Share this answer
 
v3
I would add to the correct Solution 1: "skipping" a line means reading it. In this case, this is related to the simple fact that the lines have different length. Before you can access some line, you have to read all the previous lines; before you do it, you cannot really know the position of the next line.

You just need to read lines one by one ignoring some of them. The methods like ReadToEnd or System.IO.File.ReadAllLines may or may not be suitable; not suitable if the file is too big.

—SA
 
Share this answer
 
just add .toarray on the end and it works
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 13-May-13 16:36pm    
Is it cheating, or something? Why did you pretend that you are helping someone by answering a question. Why do you self-accept formally this gibberish? If you do such things, it may cost you loosing your member account. Consider yourself warned.
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900