Search text file from end of file to beginning of file - VB.NET - vb.net

I currently have a text file that has fixed fields. There are x number of header lines and x number of detail lines. There is one piece of information I need from the detail line so I can create a record for my program. If there is a way I can loop from the end of the file to the beginning of the file I will be able to accomplish my task.
I have the code below that does the beginning of file to the end...
Using rdr As New StreamReader(_mtLocation)
Do Until rdr.EndOfStream
'// Do code here
Loop
End Using
Is there a way to go from the end of file to the beginning?
If there is any other information you need, please let me know and I will update the question with additional information. Any help is appreciated.

You can read the file into an array of String using the File.ReadAllLines method. Then you would iterate backwards through that array, which would give you each line from bottom to top. For each line, you would iterate backwards through the line.

You can read at different position of the stream by changing the Position property. The problem happens depending on the encoding of the file.
A had a simple file (not unicode) with the number 1 through 9 written into it.
Using s = System.IO.File.OpenRead("test.txt")
For i As Integer = 8 To 0 Step -1
s.Position = i
Console.WriteLine(Chr(s.ReadByte()))
Next
End Using
There's a nice example here but in C#.
stackoverflow.com/a/452945/130611

This is another solution:
Dim TxtLines As New List(Of String)
Using rdr As New StreamReader(_mtLocation)
Do Until rdr.EndOfStream
TxtLines.Add(Reader.ReadLine.ToString())
Loop
End Using
Dim x As Integer
For x = TxtLines.Count To 0 Step -1
'Do your code here...
Next
To get the text of the current line just do this inside the For loop:
TxtLines(x).ToString()

Related

how to search and display specific line from a text file vb.net

Hi I am trying to search for a line which contains whats the user inputs in a text box and display the whole line. My code below doesnt display a messsagebox after the button has been clicked and i am not sure if the record has been found
Dim filename, sr As String
filename = My.Application.Info.DirectoryPath + "\" + "mul.txt"
Dim file As String()
Dim i As Integer = 0
file = IO.File.ReadAllLines(filename)
Dim found As Boolean
Dim linecontain As Char
sr = txtsr.ToString
For Each line As String In file
If line.Contains(sr) Then
found = True
Exit For
End If
i += 1
If found = True Then
MsgBox(line(i))
End If
Next
End Sub
You should be calling ReadLines here rather than ReadAllLines. The difference is that ReadAllLines reads the entire file contents into an array first, before you can start processing any of it, while ReadLines doesn't read a line until you have processed the previous one. ReadAllLines is good if you want random access to the whole file or you want to process the data multiple times. ReadLines is good if you want to stop processing data when a line satisfies some criterion. If you're looking for a line that contains some text and you have a file with one million lines where the first line matches, ReadAllLines would read all one millions lines whereas ReadLines would only read the first.
So, here's how you display the first line that contains specific text:
For Each line In File.ReadLines(filePath)
If line.Contains(substring) Then
MessageBox.Show(line)
Exit For
End If
Next
With regards to your original code, your use of i makes no sense. You seem to be using i as a line counter but there's no point because you're using a For Each loop so line contains the line. If you already have the line, why would you need to get the line by index? Also, when you try to display the message, you are using i to index line, which means that you're going to get a single character from the line rather than a single line from the array. If the index of the line is greater than the number of characters in the line then that is going to throw an IndexOutOfRangeException, which I'm guessing is what's happening to you.
This is what comes from writing code without knowing what it actually has to do first. If you had written out an algorithm before writing the code, it would have been obvious that the code didn't implement the algorithm. If you have no algorithm though, you have nothing to compare your code to to make sure that it makes sense.

inserting data from a text file to textboxes and setting combobox indecies

so I am writing a program and trying to setup the save/open features of the program. I have the Save feature working just fine, but can't get the open feature to work.
The issue I'm running into is pulling the data from the text file to the form to fill in the multiple fields and controls. my example code is below
Imports System.IO
Main 1
Sub openFile_Click(sender, e) handles openFile.Click
Dim lineIndex As Integer = 12 'this is my total lines in my file
ofdRead.ShowDialog()
If ofdRead.FileName <> "" then
sr = New StreamReader(ofdRead.FileName)
For i As Integer = 0 To lineIndex -1
sr.ReadLine()
Next
txtField1.Text = sr.ReadLine
cboBox1.SelectedIndex = sr.ReadLine
'this continues through all fields til complete
sr.Close()
End If
End Sub
End Class
I keep getting an error for anything that is being returned as not being a string, and it seems as though the data is being read in reverse as well according to my error output.
Any help would be much appreciated (been searching and pouring over forums for 2 days looking for help)
Thanks Tim Schmelter for your insight. I was calling the wrong data type for the cboBox1 variable. Here is my corrected code (without the For-Loop, turns out i didn't need it)
cboBox1.SelectedItem = sr.ReadLine
so everytime I run into something like that I just have to tell it to put it in as a string instead of an integer

Grabbing sections of a text file - vb

Probably kick-self simple, but this is defeating me.
I have a text file which I am looking to grab in sections and populates separate text boxes. This is what the list looks like:
data_file_name
<1st section>
data
data
data
<2nd section>
data
data
data
etc.
Is there a way for me to take each section? I thought of changing the delimiter in a TextReader but some of the data also has the <> signs in it.
One way is to use system.io.file.readalllines(path) to read the file into a string array. Then process the array in memory sequentially, or using indexof, for "<1st section>", etc. This one approach of about a dozen that will work equally well.
Below is code to read each line of the file into a string. Then, you compare the string value to see if it looks like a new section. If so, do your new section code, else to your current section code
Dim reader as new streamreader(file.txt)
Dim inline as String
While reader.peek <> -1
inline = reader.readline
if inline.startswith("<") and inline.endswith(">") and inline.contains("section")
'do new section routine
else
'do current section routine
end if
end while
reader.close

VB.net generate a variable for each line in a .txt (nr. of lines unknown)

I'm trying to generate a variable for each line in a .txt file. It works for the first line but not the ones below. Would be awesome if you guys could help me proceed! This is what I have so far. I was thinking of using EOF but I couldn't get it to work -.-
Dim sr As New StreamReader(cleanfile)
Dim coins As String() = sr.ReadLine.Split(Environment.NewLine)
The number of variables must be known at compile-time. However, since the number of lines in the file can vary, you don't know this number at compile-time.
Thus, a separate variable for each line is not the solution for your problem.
Your solution is to use an array. To create one, you can simply use File.ReadAllLines:
Dim lines As String() = File.ReadAllLines(cleanfile)
Then, you can access the lines as lines(0), lines(1) or iterate through them using the For Each statement:
For Each line in lines
' Do something with line
' ...
Next

How do I remove blank lines from text File? vb.net?

I have a program I am creating and when i go to remove blank lines this is how I go about it.
For Each i As ListViewItem In lvSongs.SelectedItems
lvSongs.Items.Remove(i)
CurrentSong = i.SubItems(4).Text 'This is the Songs Path
files = File.ReadAllText("songs.txt") 'The songs path's are in the txt
'I am using this as a list of lines i want to keep in
'the txt file.
Dim linesToKeep As New List(Of String)
For Each line As String In files 'Goes through lines
If Not line.Contains(CurrentSong) Then 'checks to see if line is Current song
linesToKeep.Add(line) 'Adds line if its not CurrentSong to the list
End If
Next
File.WriteAllLines("songs.txt", linesToKeep.ToArray())
but when i go to check the txt document, i get this:
EXAMPLE (but written horizontally, each letter being on a new line)
in the text file my friend says its because i have lines set as a string instead of a string().
Thanks for anyhelp!
Ask for more information if im confusing you...
The problem is you are using the ReadAllText API. This returns a String not a String() hence when you later iterate you are iterating over every character in the file, not every line. To fix this use the ReadAllLines API which returns a String()
files = File.ReadAllLines("songs.txt")
Note I can't tell if files is an implicitly declared local or a field. If it's a field typed to String you will need to change the type to String().