Massattack01
Massattack01

Reputation: 1

Count lines before specified string of Text File? In VB

is there a way to count the amount of lines before a specific line / string in a text file. For Example:

1

2

3

4

5

6

7

8

9

Say i want to count the amount of line before '8'... How would i do that?

thanks!

Upvotes: 0

Views: 494

Answers (2)

sujith karivelil
sujith karivelil

Reputation: 29006

Hope that this actually you are looking for, it will read all lines from a file specified. then find the IndexOf particular line(searchText) then add 1 to it will gives you the required count since index is0based.

    Dim lines = File.ReadAllLines("f:\sample.txt")
    Dim searchText As String = "8"
    msgbox(Array.IndexOf(lines, searchText) + 1)

Upvotes: 2

Idle_Mind
Idle_Mind

Reputation: 39122

Here's another example using List.FindIndex(), which allows you to pass in a Predicate(T) to define how to make a match:

    Dim fileName As String = "C:\Users\mikes\Documents\SomeFile.txt"
    Dim lines As New List(Of String)(File.ReadAllLines(fileName))
    Dim index As Integer = lines.FindIndex(Function(x) x.Equals("8"))
    MessageBox.Show(index)

In the example above, we're looking for an exact match with "8", but you can make the predicate match whatever you like for more complex scenarios. Just make the function (the predicate) return True for what you want to be a match.

For example, a line containing "magic":

    Function(x) x.ToLower().Contains("magic")

or a line that begins with a "FirstStep":

    Function(x) x.StartsWith("FirstStep")

The predicate doesn't have to be a simple string function, it can be as complex as you like. Here's one that will find a string that ends with "UnicornFarts", but only on Wednesday and if Notepad is currently open:

    Function(x) DateTime.Today.DayOfWeek = DayOfWeek.Wednesday AndAlso Process.GetProcessesByName("notepad").Length > 0 AndAlso x.EndsWith("UnicornFarts")

You get the idea...

Using a List, instead of an Array, is good for situations when you need to delete and/or insert lines into the contents before writing them back out to the file.

Upvotes: 1

Related Questions