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

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

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.

Search text file from end of file to beginning of file - 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()

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

What am I doing wrong when splitting lines from a textfile

I am working on a quiz for my computer science program and the idea is having keywords and definitions. The User will be shown a keyword that gets randomized and three definitions in radiobuttons, one must be the correct answer.
I decided to put my keywords and my defintions in the same file like so:
Keyword1 = Definition1
Keyword2 = Definition2
Keyword3 = Definition3
etc.
On my main form I have the following loop:
For Each line As String In System.IO.File.ReadAllLines("my-file-path-here")
Dim Pair() As String = line.split("=")
LabelKeyword.text = Trim(Pair(0)) ' Needs Randomizing
RadioButtonDef1.text = Trim(Pair(1)) ' Needs randomizing
'RadioButtonDef2.text = 'Don't know needs randomizing
'RadioButtonDef3.text = 'Don't know needs randomizing
Next
What I can't seem to figure out is how to randomize the keywords and the definitions. Also I have 15 lines in my text file and it always seems to only read the last line.
So my questions are:
How can I randomize the keywords and the definitions always having one of the definitions the answer to the current keyword.
Why does it only read the very last line of my text file and how can I fix it?
I also need to be able to make the quiz only finish when every keyword has been matched to its definition twice. Their time taken also needs to be recored as they play.
You are looping through all of the lines in your text file, but you are displaying all of them in the same control. Therefore, each time you iterate through the loop, it overwrites the values in the controls from the last iteration. I would strongly suggest storing your values in some sort of data-structure in memory. Then you can access the values randomly at will. For instance, you could store all the values in a Dictionary, like this:
Dim dict As New Dictionary(Of String, String)()
For Each line As String In File.ReadAllLines("...")
Dim pair() As String = line.Split("=")
dict(pair(0)) = pair(1)
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().