Textfieldparser Delimiters - vb.net

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)))

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.

Visual Basic Append to a specific point in a text file

I am currently trying to manipulate a line in a file that we are using to retain data, using comma delimiters. For example -
121,1212, XJAY,Sean K,Kean S,AAAA-BBBB-AAAA-BBBB-AAAA
12456,987654,WYST,Steve Jobs,Bill Gates,CAAA-BBBB-AAAA-BBBB-AAAA
If I assume that the last line is always a unique code, is it possible to identify that line in the text file and append it with another field?
Prior research has been reading through the APIs for StreamReader and StreamWriter, and looking through other StackOverflow questions, however most questions seem focused on just appending to the end of the file, or in different languages!
As always thank you for your time, and if there is anything I've left off please let me know!
You can't manipulate a line in a file in any reasonably easy way.
There are no methods to work with lines in a file, because files are not line based. They are not even character based. The bytes in the file are decoded into characters, then the line break characters are recognised and the characters can be split into lines.
The easiest way to manipulate a line is to read the entire file into a string array, change the string that you want change, then write the entire string array to the file.
Example:
Dim fileName As String = "c:\data.txt"
Dim lines As String() = File.ReadAllLines(fileName)
For i As Integer = 0 To lines.Length - 1
Dim line As String = lines(i)
If line.StartsWith("12456,") Then
lines(i) = line & ",More data"
End If
Next
File.WriteAllLines(fileName, lines)
If you are looking for a way to parse Each line with StreamReader and StreamWriter: Here it is:
'You will need Imports System.IO
Dim TheNewFile As String
Dim MyLine As String
Dim MyStream2 As New FileStream("C:\Your Directory\YourFile.txt", FileMode.Open)
Dim MyReader As New StreamReader(MyStream2)
Dim MySettings As New StringReader(MyReader.ReadToEnd)
MyReader.BaseStream.Seek(0, SeekOrigin.Begin)
MyReader.Close()
MyStream2.Close()
Try
Do
MyLine = MySettings.ReadLine
'This if statement is an exit parameter. It can be if it contains or if 5 consecutive lines are nothing. It could be a number of things
If MyLine Is Nothing Then Exit Do
'This is the file you will write. You could do if MyLine = "Test" Then ........... append whatever and however you need to
TheNewFile = TheNewFile & MyLine & vbCrLf
Loop
Catch ex As Exception
MsgBox(ex.ToString())
End Try
'-----------------Write The new file!!!----------------
Dim MyStream3 As New FileStream("C:\Where you want to write New File\NewFileName.txt", FileMode.Create)
Dim MyWriter3 As New StreamWriter(MyStream3)
MyWriter3.Write(TheNewFile & "Test")
MyWriter3.Close()
MyStream3.Close()

StreamReader not finding end of file

I simply need to read lines from a text file and show them. When I run this I can see that id does what I want, but after it reads the last value it just shows a blank form on my screen and does not move on. It seems like it can't find the end of the file or something. I don't get an error.
Using sr As New System.IO.StreamReader(Application.StartupPath & "\myfile.cfg")
Dim Line As String = ""
Dim i As Integer = 0
Dim temp_array As Array
Do While Line IsNot Nothing
Line = sr.ReadLine
temp_array = Line.Split("=")
'MessageBox.Show(temp_array(0))
Loop
End Using
That is bad code because you're actually going to use Line before testing whether it's Nothing. Here are two good options for looping through the lines of a text file:
Using reader As New StreamReader(filePath)
Dim line As String
Do Until reader.EndOfStream
line = reader.ReadLine()
'...
Loop
End Using
For Each line In File.ReadLines(filePath)
'...
Next
As you can see, the second is far more concise but it does require .NET 4.0 or later.

Words from text file as variables in a checkedlistbox

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

How to replace CRLF with a space?

How can I parse out undesireable characters from a collection of data?
I am working with existing VB.NET code for a Windows Application that uses StreamWriter and Serializer to output an XML document of transaction data. Code below.
Private TransactionFile As ProjectSchema.TransactionFile
Dim Serializer As New Xml.Serialization.XmlSerializer(GetType (ProjectSchema.TransactionFile))
Dim Writer As TextWriter
Dim FilePath As String
Writer = New StreamWriter(FilePath)
Serializer.Serialize(Writer, TransactionFile)
Writer.Close()
The XML document is being uploaded to another application that does not accept "crlf".
The "TransactionFile" is a collection of data in a Class named ProjectSchema.TransactionFile. It contains various data types.
There are 5 functions to create nodes that contribute to the creation of a Master Transaction file named TransactionFile
I need to find CRLF characters in the collection of data and replace the CRLF characters with a space.
I am able to replace illegal characters at the field level with:
.Name = Regex.Replace((Mid(CustomerName.Name, 1, 30)), "[^A-Za-z0-9\-/]", " ")
But I need to scrub the entire collection of data.
If I try:
TransactionFile = Regex.Replace(TransactionFile, "[^A-Za-z0-9\-/]", " ")
Because TransactionFile cannot be converted to String I get a "Conversion from type 'Transaction' to type 'String' is not valid" message.
Bottom Line = How can I replace CRLF with a space when it shows up in TransactionFile data?
Don't do it this way. Create the serializer with XmlWriter.Create(). Which has an overload that accepts an XmlWriterSettings object. Which has lots of options to format the generated XML. Like NewLineChars, it lets you set the characters to use for a line end.
As Hans says, mess around with the XmlWriterSettings.
The next best choice is to write the file, then read the file into an xml object and process it element by element. This would let you remove crlf from within individual elements, but leave the ones between elements alone, for example.
Another possibility - rather than write directly to the file, you can make an intermediate string, and do a replace in that:
Dim ms As New MemoryStream
Serializer.Serialize(ms, TransactionFile)
ms.Flush()
ms.Position = 0
Dim sr As New StreamReader(ms)
Dim xmlString As String = sr.ReadToEnd
sr.Close() ' also closes underlying memorystream
Then you could do your regex replace on the xmlString before writing it to a file. This should get all the crlf pairs, both within elements and between.