VBNET Reading a specific column on a line in a text file - vb.net

I have saved written a text file and it currently reads:
"first","surname","pass"
I want to read the password column so the 3rd one and define that as a variable. Its basically for a login, if pass in text file matches the entered pass (from user).
I have searched for about an hour now and no luck. Could someone guide me to a correct path.
Thanks.

Simple example of reading a small file line by line and splitting each one into fields:
' get the values from the user somehow:
Dim first As String = "James"
Dim surname As String = "Bond"
Dim pass As String = "007"
Dim validated As Boolean = False ' assume wrong until proven otherwise
' check the file:
Dim fileName As String = "c:\some folder\path\somefile.txt"
Dim lines As New List(Of String)(System.IO.File.ReadAllLines(fileName))
For Each line As String In lines
Dim values() As String = line.Split(",")
If values.Length = 3 Then
If values(0).Trim(Chr(34)) = first AndAlso
values(1).Trim(Chr(34)) = surname AndAlso
values(2).Trim(Chr(34)) = pass Then
validated = True
Exit For
End If
End If
Next
' check the result
If validated Then
MessageBox.Show("Login Successful!")
Else
MessageBox.Show("Login Failed!")
End If

If this is a CSV file, as seems to be the case, then the easiest way to read it will be with the TextFieldParser class. The MSDN already provides an excellent example for how to use it to read a CSV file, so I won't bother reproducing it here.

Related

Saving contents of multiple text boxes and possibly combo boxes

I'm working on a basic application that lets you track experience earned across up to 3 skills. The names of the skills are in a combo box (not sure if the best) and the beginning and ending values are in text boxes.
I want to add a save button that saves the ending values and selected skills, when pressing the load button it would populate the combo boxes with saved skills and input the old ending values into the new beginning ones.
I've been working on this all day, searching for a long time I've come up with similar solutions but nothing seems to work right. I'm still a bit of a beginner so some of the solutions I don't understand. Also, this has to work for VBNet.
The closest solution I've come across is:
File.WriteAllText("C:\Data.txt", String.Join("|", new String({TextBox1.Text, TextBox2.Text, TextBox3.Text}))
I'd like the file to stay with the project in the main directory though. Would this work for combo boxes as well, and how to load the values back in?
I'm still a newbie to VB, hope this question makes sense.
If I get your idea right, please find some functions below if they can help:
One can read (or write) text:
This one can populate the needed string to 3 textboxes txtSkill1, txtSkill2, txtSkill3
Sub ReadTextFile()
Dim lineCount As Integer = 0
Dim rndInstance As New Random
Dim idx As Integer = 0
Dim selectedLine As String = ""
Dim txt As String = "Skills.txt"
If Not File.Exists(txt) Then
File.Create(txt).Dispose()
Dim objWriter As New System.IO.StreamWriter(txt, True)
' 2 sample text lines:
objWriter.WriteLine("Negotiating - Interpersonal - Working independently")
objWriter.WriteLine("Goal oriented - Leadership - Teamwork")
objWriter.Close()
End If
lineCount = File.ReadAllLines(txt).Length
idx = rndInstance.Next(1, lineCount + 1) ' the index can be random if you want, or run from (1 to lineCount)
selectedLine = ReadLineWithNumberFrom(txt, idx)
Dim pattern As String = "-" ' split on hyphens
Dim subStrings() As String = Regex.Split(selectedLine, pattern)
txtSkill1.Text = subStrings(0)
txtSkill2.Text = subStrings(1)
txtSkill3.Text = subStrings(2)
End Sub
One can read a string from a specific line number:
Function ReadLineWithNumberFrom(filePath As String, ByVal lineNumber As Integer) As String
Using file As New StreamReader(filePath)
' Skip all preceding lines:
For i As Integer = 1 To lineNumber - 1
If file.ReadLine() Is Nothing Then
Throw New ArgumentOutOfRangeException("lineNumber")
End If
Next
' Attempt to read the line you're interested in:
Dim line As String = file.ReadLine()
If line Is Nothing Then
Throw New ArgumentOutOfRangeException("lineNumber")
End If
' Succeeded!
Return line
End Using
End Function
Now with the functions allow you to write to any text file, to read from any text file, from any line number, with specific separator (here is the hyphen -- char), you can Save and Load any string you need.

VB.net How to remove quotes characters from a streamReader.readline.split()

I had built a project that read data from a report and it used to work fine but now for some reason the report puts every thing in to strings. So I want to modify my stream reader to remove or ignore the quotes as it reads the lines.
This is a snipet of the part that reads the lines.
Dim RawEntList As New List(Of Array)()
Dim newline() As String
Dim CurrentAccountName As String
Dim CurrentAccount As Account
Dim AccountNameExsists As Boolean
Dim NewAccount As Account
Dim NewEntry As Entrey
Dim WrongFileErrorTrigger As String
ListOfLoadedAccountNames.Clear()
'opens the file
Try
Dim sr As New IO.StreamReader(File1Loc)
Console.WriteLine("Loading full report please waite")
MsgBox("Loading full report may take a while.")
'While we have not finished reading the file
While (Not sr.EndOfStream)
'spliting eatch line up into an array
newline = sr.ReadLine.Split(","c)
'storring eatch array into a list
RawEntList.Add(newline)
End While
And then of course I iterate through the list to pull out information to populate objects like this:
For Each Entr In RawEntList
CurrentAccountName = Entr(36)
AccountNameExsists = False
For Each AccountName In ListOfLoadedAccountNames
If CurrentAccountName = AccountName Then
AccountNameExsists = True
End If
Next
You could just do
StringName.Replace(ControlChars.Quote, "")
or
StringName.Replace(Chr(34), "")
OR
streamReader.readline.split().Replace(Chr(34), "")
How about doing the replace before the split, after the readline? That should save iteration multiplication, or better yet (if possible), do a replace on the entire file (if the data is formatted in the way it can be done & you have enough memory) using the ReadAllText method of the File object, do your replace, then read the lines from memory to build your array (super fast!).
File.ReadAllText(path)

How do I read a tab delimited file to find the line which has a known value?

I have a tab delimited file which has data like this...
022j<TAB>10.375
023j<TAB>12.365
024j<TAB>15.230
NOTE: this will not let me post as it is... each 02xj is a different line in the text file. It
EG: 023j is input into a textbox.
Need to find the value associated with the input; 12.365 in this case.
There are a few different files (some are encoded 012j, 012#, 012$ etc. which will correspond to different data.)
My head is exploding trying to find a way to take what I have in the textbox then read through and find the data I need.
I know this is easy, please nudge me in the right direction.
Here's your nudge. You should be able to use something like this:
Dim searchValue As Decimal = 023j 'or someTextBox.Text whatever
Dim searchField As Int32 = 0
Dim returnField As Int32 = 1
Dim returnValue As String = ""
Dim returnLineNumber as Int32 = 0
Using fileReader As New FileIO.TextFieldParser(YourFileNameWithPathAsString)
fileReader.TextFieldType = FileIO.FieldType.Delimited
fileReader.SetDelimiters(vbTab)
While Not fileReader.EndOfData
Dim currentLine As String() = fileReader.ReadFields()
If currentLine(searchField) = searchValue Then
returnValue = currentLine(returnField)
returnLineNumber = fileReader.LineNumber
Exit While
End If
End While
End Using
Return returnValue 'or Return returnLineNumber if that is what you need
You should be able to make it a function and if no result is returned then check your next file.
I figured this out... so this is what I ended up doing.
First set up the streamreader
'set reader to read the file
Dim reader As New System.IO.StreamReader(filetoread)
Then loop through the file line by line, use contains to find the string to match. Do whatever trimming/extracting and you're there.
Do While reader.Peek() >= 0
line = reader.ReadLine
If line.Contains(TB_Input.Text) Then
s = Replace(line, TB_Input.Text, "")
s = Replace(s, vbTab, "")
TB_Length.Text = s
End If
Loop
I was leaking brain juice on this. Until someone basically said "just do it"... thanks I needed that.
I know there are things like variables I don't explain... I figured anyone looking will know, if that's a bad assumption let me know.
Thanks again

How to read from a 2-line text file and output each line to 2 variables in vb.net

Hello in my program I need for a text file containing 2 lines to be read and each line's contents to be put into their own variable. the text file is called "account.txt" and is under the directory Documents. the code i have curently that sees if it exists is this:
If File.Exists(System.IO.Path.Combine(My.Computer.FileSystem.SpecialDirectories.MyDocuments, "Account.txt")) Then
MsgBox("Account found and is being loaded!")
End If
I would like in that if statement for the file to be read and each line to be read and contents to be put into their own variable. Any help is greatly appreciated!
You could either use a collection like String() or List(Of String) or read them with File.ReadLines or File.ReadAllLines and assign index 0 to variable 1 and index 1 to variable 2:
Dim path = Path.Combine(My.Computer.FileSystem.SpecialDirectories.MyDocuments, "Account.txt")
If File.Exists(path) Then
Dim allLines = File.ReadAllLines(path)
Dim line1 As String = allLines(0) ' indices are zero based
Dim line2 As String = allLines(1)
End If
You can also use ElementAtOrDefault(1) instead of allLines(1) if you're not sure if the file contains two lines at all. It'l be Nothing if it contains less:
Dim line2 As String = allLines.ElementAtOrDefault(1) ' can be Nothing
If File.Exists(System.IO.Path.Combine(My.Computer.FileSystem.SpecialDirectories.MyDocuments, "Account.txt")) Then
Dim accountReader As StreamReader = new StreamReader(My.Computer.FileSystem.SpecialDirectories.MyDocuments, "Account.txt")
Dim line1 As String = accountReader.ReadLine()
Dim line2 As String = accountReader.ReadLine()
reader.Close()
End If
This should work, have not tested it I usually work on C# so I tried to convert it to VB.Net I usually prefer to reader all lines into arrays and before assigned to it I do all necessary checks but this should get you started.
I seperated it like this since you mentioned that you want line contents into different variables.
Hope this helps you :)

String.Contains Function in Visual Basic 2008 or 2012

How do I find a unique string that contains in a single .txt file with different strings in each line?
Example:
The .txt file contains the following
012345
023456
034567
045678
056789
Then I want to find one of the set of numbers.
This is what I want to happen~
Dim stN As String = TextBox1.Text
If stN.contains(.txt file) Then
'Anything to do here
Else
MsgBox("Your input number is incorrect", "ERROR")
End If
I assume your pseudo code should be the other way around: If .txt-file.Contains(stN) Then.
So you want to know if a string equals one line of a text-file:
Dim lines = File.ReadLines(path)
Dim fileContainsLine = lines.Any(Function(l) l.Trim.Equals(TextBox1.Text, StringComparison.OrdinalIgnoreCase))
If you don't want to compare case-insensitively use l==TextBox1.Text instead. If the Trim is also unnecessary you could simplify it to:
Dim fileContainsLine = lines.Contains(TextBox1.Text)
Here is a little Linqpad program, but you would probably want to read in the file one time and cache it.
Sub Main
If (CheckContains("023456")) Then
Console.WriteLine("True")
Else
Console.WriteLine("False")
End If
End Sub
Function CheckContains(inputVal as String) as Boolean
Dim query = From line In File.ReadAllLines("C:\code\so\sample.txt") _
Select line
return query.Contains(inputVal)
End Function