Words from text file as variables in a checkedlistbox - vb.net

I have discovered how to take a text file and put it in an checkedlistbox. Now I want to apply variables to each item in the checkedlistbox also using a text file.
This is the code I used.
Imports System.IO 'Top of the source code
Dim sr As New StreamReader("C:\Users\Me\Desktop\test.txt")
Dim word As String = ""
Dim words(9) As String
Dim i As Integer = 0
Do Until sr.Peek = -1
word = sr.ReadLine()
words(i) = word
Vlanbx1.Checklisbox.Items.Add(words(i))
Vlanbx2.Checklisbox.Items.Add(words(i))
i = i + 1
Loop
I would like to have both the checkedlistbox items and the variables in the same text file side by side.
My main goal is to have a list that when it is changed in the text file is updates when the form is opened. But I am unsure how to grab the variables to the text and apply them to their adjacent Items from the list.
Any guidance, please.

Your code works without problem only if your file has no more that 10 lines.
You could change it in this way
Imports System.IO
....
Dim words = File.ReadLines("C:\Users\Me\Desktop\test.txt").ToList()
For Each word in words
Vlanbx1.Checklisbox.Items.Add(word)
Vlanbx2.Checklisbox.Items.Add(word)
Next
Now the File.ReadLines returns all the lines of your file in a List(Of String) then you could loop over this List and add the words one by one to your CheckedListBoxes
EDIT
Following your comment, if you have a line composed of two words separated by a space and the first word should be stored in the checkedlistbox while the second one in a internal list of words, then your code should change to
Imports System.IO
....
Dim listOfSecondWords = new List(Of String)()
Dim lines = File.ReadLines("C:\Users\Me\Desktop\test.txt").ToList()
For Each line in lines
Dim words = line.Split(" "c)
Vlanbx1.Checklisbox.Items.Add(words(0))
Vlanbx2.Checklisbox.Items.Add(words(0))
listOfSecondWords.Add(words(1))
Next
A bit of error control should be added to be really sure that you have two words for each line checking the length of the array words obtained splitting the line at the first space character

Related

Deleting all lines in text file until you get to a word vb.net

Very new to vb.net, apologies if this is basic. I am trying to open up a text file and delete all the lines starting at index 0 until I hit the line that has the word I am looking for. Right now, it just deletes the word I put in it.
' Read the file line by line
Using reader As New IO.StreamReader(fileName)
While Not reader.EndOfStream()
Dim input As String = reader.ReadLine()
'Delete all lines up to String
Dim i As Integer
i = 0
For i = 0 To input.Contains("{MyWord}")
builder.AppendLine(input)
Next
End While
End Using
Partial. You didn't say what to do with the rest of the lines...
Did you mean lines?
Dim ShouldRead as Boolean
Dim builder As New System.Text.StringBuilder
Using reader As New IO.StreamReader(fileName)
'Delete all lines without String
While Not reader.EndOfStream()
Dim input As String = reader.ReadLine()
If input.Contains("{MyWord}") Then ShouldRead = True
If ShouldRead Then
builder.AppendLine(input)
End If
End While
End Using
I would tend to do it like this:
Dim lines = File.ReadLines(filePath).
SkipWhile(Function(line) Not line.Contains(word)).
ToArray()
File.WriteAllLines(filePath, lines)
The File.ReadLines method reads the lines of the file one by one and exposes them for processing as they are read. That's in contrast to the File.ReadAllLines method, which reads all the lines of the file and returns them in an array, at which case you can do as desired with that array.
The SkipWhile method will skip the items in a list while the specified condition is True and expose the rest of the list, so that code will skip lines while they don't contain the specified word and return the rest, which are then pushed into an array and returned. That array is then written back over the original file.
Just note that String.Contains is case-sensitive. If you're using .NET Core 2.1 or later then there is a case-insensitive overload but older versions would require the use of String.IndexOf for case-insensitivity.

How to keep the content of ListBox in Vb.net

If i want to keep the content of a textbox i do this
TextBox1.Text = TextBox1.Text & Something
Is there a way to do the same thing for the content of Items of a Listbox?
In my RichTextBox3 i have the list of files in the C:\Work directory
I Tried this code but it's giving me The content of the last line (It's not adding the lines before)
Do Until number = RichTextBox3.Lines.Length
Dim directory = "C:\Work\" & RichTextBox3.Lines(number)
Dim files() As System.IO.FileInfo
Dim dirinfo As New System.IO.DirectoryInfo(directory)
files = dirinfo.GetFiles("*", IO.SearchOption.AllDirectories)
For Each file In files
ListBox1.Items.Add(file)
Next
number = number + 1
Loop
Help is appreciated
Thanks to all of you
I'm not sure that this will address your stated problem but there's a serious issue with that code and I need to provide a long code snippet to address it and that won't be readable in a comment.
The Lines property of a TextBox or RichTextBox is not "live" data, i.e. it doesn't refer to an array stored within the object. Each time you get the property, a new array is created. You are getting RichTextBox3.Lines twice for every iteration of that loop, so that's obviously wrong. You also should not be adding items to the ListBox one by one like that. You should be creating a list of all the items first, then adding them all with a single call to AddRange:
Dim files As New List(Of FileInfo)
For Each line In RichTextBox3.Lines
Dim folderPath = Path.Combine("C:\Work", line)
Dim folder As New DirectoryInfo(folderPath)
files.AddRange(folder.GetFiles("*", SearchOption.AllDirectories))
Next
ListBox1.Items.AddRange(files.ToArray())
If that code doesn't work as expected, you can debug it and view the contents of files at various stages to make sure that you are getting the files you expect. It might also be worth testing folder.Exists before calling GetFiles, unless you're absolutely sure that each line in the RichTextBox represents an existing folder.
This will do what you want.
number = 0
ListBox1.items.clear()
Do Until number = RichTextBox3.Lines.Length
Dim directory = "C:\Work\" & RichTextBox3.Lines(number)
Dim files() As System.IO.FileInfo
Dim dirinfo As New System.IO.DirectoryInfo(directory)
files = dirinfo.GetFiles("*", IO.SearchOption.AllDirectories)
For Each file In files
ListBox1.Items.Add(file)
Next
number = number + 1
Loop

Reading and writing lines to and from a file

I am writing a simple console application using Microsoft Visual Basic 2010 express. I am trying to make a "newfile1.txt" file in which will be write something heading and than lets say 10 rows with three words in each row.
After that, I would like to read from file, and write to the "newfile2" file only the second word from file "newfile1.txt"
Than I would like to read from this file every line, and store lets and store only the second word from newfile1.txt
I try to use following code but I don't know how to specify several things (see bellow code)
Module Module1
Sub Main()
Dim i As Integer
FileOpen(1, "C:\Users\Namba\Documents\ANALYZA MD\newFile1.txt", OpenMode.Append, OpenAccess.ReadWrite, OpenShare.Default)
FileOpen(2, "C:\Users\Namba\Documents\ANALYZA MD\newFile2.txt", OpenMode.Append, OpenAccess.ReadWrite, OpenShare.Default)
WriteLine(1, "Heading of the file1")
For i = 1 To 10 Step 1
WriteLine(1, "Word 1" & "Word 2" & "Word 3")
Next
FileClose(1)
WriteLine(2, "Heading of the file2")
Dim filereader As System.IO.StreamReader
filereader = My.Computer.FileSystem.OpenTextFileReader("C:\Users\Namba\Documents\ANALYZA MD\newFile1.txt")
Dim stringReader As String
For i = 1 To 10 Step 1
stringReader = filereader.ReadLine()
WriteLine(2, stringReader)
Next
End Sub
End Module
So I have several questions:
Is it possible via ReadLine store words lets say in to the array or each word to the different string variable?
Is there simpler form how to open file and read each word, eventual define that the first word will be store in to the string var1, the second in to the var2 and so on, and similar if we have a file with numbers so that I would like to read from this file and store each number in to the some variable.
I can do this in fortran easy, via READ() WRITE() in very simple way
OPEN(UNIT=11, FILE="newfile1.txt)
READ(UNIT=11) x, y, z
OPEN(UNIT=12, FILE="newfile2.txt)
WRITE(UNIT=12,*) y
So this will read from one file the first 3 word(or number if the x, y, z is declare as number) from the first line and write in to the second file just second word (or number).
So I wonder if there is something very similar also in visual basic?
In general, if your files aren't large then it is faster (with respect to code writing) and easier to just read the contents of the file into memory and then manipulate it as needed.
Hopefully these examples will be of some help.
' Read entire contents of file1.txt into an array.
Dim file1 As String() = System.IO.File.ReadAllLines("C:\file1.txt")
' Now extract the 2nd word from each line (assuming all lines have at least 2 words).
Dim secondWords As New List(Of String)
For Each line In file1
' Break apart the string by spaces and take the second index (word).
secondWords.Add(line.Split(" ")(1))
Next
' Write the contents to a new file.
' This new file will have 1 word per line.
System.IO.File.WriteAllLines("C:\file2.txt", secondWords.ToArray())
If you are looking to examine each word, the code can become something like this:
' Read entire contents of file1.txt into an array.
Dim file1 As String() = System.IO.File.ReadAllLines("C:\file1.txt")
' Process each line.
For Each line In file1
' Process each word within the line.
For Each word In line.Split(" ")
' Do something with the word.
Console.WriteLine(word)
Next
' Or process by word index.
Dim words As String() = line.Split(" ")
For i As Integer = 0 To words.Length - 1
Console.WriteLine(String.Format("Word {0} is {1}", i + 1, words(i)))
Next
Console.WriteLine("Moving to a new line.")
Next

Saving Columns of listview in VB with separator

So I have a listview which has two columns. the listview view is details.
I have successfully imported a file into the list view with correct splits. The code i used is,
Using sr As StreamReader = File.OpenText( file path )
While (-1 < sr.Peek())
Dim line As String = sr.ReadLine()
Dim item As New ListViewItem(line.Split(":"c))
ListView1.Items.Add(item)
End While
sr.Close()
End Using
So this imports the lines from my file to the program into correct columns with : as split.
Now I also have a option for users to add data from my program to the file the same way, I used this code,
Using sw As StreamWriter = File.AppendText(file path)
For Each item As ListViewItem in ListView1
Dim line As String = Nothing
For Each entry As String in item.SubItems
line.Append(entry & ":")
Next For
sw.WriteLine(line)
Next For
sw.Close()
End Using
Taken from : Separating text from .txt into colums in listview (VB.net mobile)
But my bad, vb gives this error,
Error 1 Expression is of type 'System.Windows.Forms.ListView', which is not a collection type. C:\Users\xxxx\documents\visual studio 2012\xxxxx\Form1.vb 97
I am not sure why i am getting this error, is it because of my list views properties ?
I want to be able to save the data to the text file when user click a button.
This line:
For Each item As ListViewItem in ListView1
should be this:
For Each item As ListViewItem in ListView1.Items
and this line:
For Each entry As String in item.SubItems
should be this:
For Each entry As ListViewItem.ListViewSubItem in item.SubItems
You then get a String from the Text property of the subitem.

Textfieldparser Delimiters

I'm currently busy coding a hangman game in VB.NET.
As a wordlist, I have a textfile containing 1520 words, each one seperated by a new line...
The best I could think of to get a random word is with a Randomize() function.
Then getting the word from the line # which was randomly generated.
Only to find out just now, that this method:
Using parser As New Microsoft.VisualBasic.FileIO.TextFieldParser_
("filepath")
parser.TextFieldType = FileIO.FieldType.Delimited
doesn't allow me to use a new line as a delimiter...
Considering all words have different lengths/widths, I can't use this either:
parser.TextFieldType = FileIO.FieldType.FixedWidth
Is there any better way for me to extract the word from that random line?
If not, what would be the delimiter I should use for this and how do I quickly change the breaklines into that new delimiter without resorting to Office?
Also, how can I use the textfieldparser to get the file from resources?
When I tried using
my.resources.filename
instead of "filepath", it gave me an ArgumentException due to "invalid characters in the path".
The easier way is to load your text file into a string collection, then grab the random index of the collection
Dim list As New List(Of String)
Dim Reader As New StreamReader("C:\WordList.txt")
Dim line As String
Do
line = Reader.ReadLine()
list.Add(line)
Loop Until line Is Nothing
Reader.Close()
Read all the words into a string array with File.ReadAllLines. One line of code:
Dim words() As String = File.ReadAllLines(path)
To select a random word, use Rnd
Randomize()
Dim randomWord As String = words(CInt(Math.Floor(Rnd * words.Length)))