Reputation: 125
I have a problem with my .txt file. It has the same text in it except the one says "Kleur", and the other says "Binair".
I need to read all the lines in that .txt file but need to skip the lines with the word "kleur" in it.
Here is a sample of my code:
For Each f In dinfo.GetFiles("*.txt", SearchOption.AllDirectories)
Using sr As New StreamReader(f.FullName)
Dim findstring = IO.File.ReadAllText(f.FullName)
Dim Lookfor As String = "Binair"
If findstring.Contains(Lookfor) Then
End If
But this doesn't skip the kleur lines and the code still does thing to it.
Can someone help me to skip those lines, and only work with the lines "binair" in it?
Upvotes: 0
Views: 767
Reputation: 216303
If you want to apply some logic line by line skipping the unwanted lines, then read the file line by line or process the lines one at time after reading them in memory (the choice depends on file size)
This approach uses the IEnumerable extension Where on the lines returned by ReadLines (who returns an IEnumerable of your lines and doesn't load them all in memory).
For Each f In dinfo.GetFiles("*.txt", SearchOption.AllDirectories)
Dim lines = File.ReadLines(f.FullName).
Where(Function(x) Not x.Contains("Kleur"))
' lines contains only the lines without the word Kleur
For Each l As String In lines
' Process the lines
Next
Next
But you can also use a StreamReader to read a single line, process it if required, then loop for the next line
Dim line As String = ""
For Each f In dinfo.GetFiles("*.txt", SearchOption.AllDirectories)
Using sr = New StreamReader(f.FullName)
While True
line = sr.ReadLine
If line IsNot Nothing Then
If Not line.Contains("Kleur") Then
' process the line
End If
Else
Exit While
End If
End While
End Using
Next
Finally you can load everything in memory and process from there (but pay attention to the size of the file)
Dim line As String = ""
For Each f In dinfo.GetFiles("*.txt", SearchOption.AllDirectories)
Dim lines = File.ReadAllLines(f.FullName)
For each line in lines
if Not line.Contains("Kleur") Then
' process the line
End If
Next
Next
Upvotes: 1