Joshua Cummings
Joshua Cummings

Reputation: 145

Read only lines longer than a certain amount from .txt file

I've been searching the net for a while trying to find out how to simply read only lines longer than 0 characters from a .txt file into a listbox in VB. I am using VS 2010 and want to read only lines that contain content into the list box.

For example I want to only read the lines labeled 1.

1
1


1
1

1

Upvotes: 1

Views: 295

Answers (2)

Victor Zakharov
Victor Zakharov

Reputation: 26434

You can use a combination of ReadAllLines and LINQ:

ListBox1.DataSource = IO.File.ReadAllLines("file.txt").Where(Function(x) x.Length > 0).ToList

To start at the 3rd line, use Skip:

IO.File.ReadAllLines("file.txt").Skip(2).Where(Function(x) x.Length > 0).ToList

Upvotes: 2

Tim Schmelter
Tim Schmelter

Reputation: 460228

So you just want to add lines with text:

Dim notEmptyLines = From line In IO.File.ReadLines(path)
                    Where Not String.IsNullOrWhiteSpace(line)

For Each line In notEmptyLines
    ListBox1.Items.Add(line)
Next

Replace Not String.IsNullOrWhiteSpace(line) with line.Length <> 0 if you also want to count white-spaces.

Upvotes: 0

Related Questions