Reading TXT file line by line (VB 2010) - vb.net

I have a program written to be a username/password creator, and there is a section that I am attempting to make that will determine whether the entered username is taken or not, and inform the user. It doesn't seem to be working. My code is as follows:
z = File.OpenText(a)
Do Until z.EndOfStream() = True
Dim password As String
password = CStr(z.ReadLine() & vbCrLf)
If password = TextBox1.Text Then
errors = errors + 1
msgPrompt = msgPrompt & "The username you entered, " & TextBox1.Text & " is already taken."
End If
If errors > 1 Then
TextBox5.Text = errors & " errors occured."
ElseIf errors = 0 Then
TextBox5.Text = "No errors!"
Else
TextBox5.Text = errors & " error occured."
End If
If errors >= 1 Then
Button2.Enabled = True
Else
Button2.Enabled = False
End If
Loop
The passwords are stored line by line in a .txt file, so basically I want the program to go over each entry one by one and see if it matches what the user entered. If I am doing something wrong, please inform me, I'd love to get this script working.

Assuming that the heading of your question is correct, your variables in your code are named incorrectly - This isn't vitally important, but it will confuse whoever comes back in 6 months to maintain the software. Also, when your code is running correctly, as all the usernames will be unique, there is no need to return the number of errors.
It is longer than your original code, but the TextExists function can be used to open the file of your choosing such as the password file and the username file - Though your usernames and password in this situation are better stored in the one file.
'Opens the file and if it contains the input text, returns True. Otherwise returns false
Private Function TextExists(filename As String, inputText As String) As Boolean
Dim z As StreamReader = File.OpenText(filename)
Dim fileText As String
Dim msgPrompt As String = ""
Do Until z.EndOfStream() = True
fileText = CStr(z.ReadLine())
If inputText = fileText Then
Return True
End If
Loop
Return False
End Function
Private Sub CheckUserName()
If TextExists(a, TextBox1.Text) Then
MessageBox.Show("Username Already Exists")
Button2.Enabled = False
Else
Button2.Enabled = True
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
CheckUserName()
End Sub
For serious storage of passwords the username and passwords should be encrypted before they are saved of course, and decrypted when loaded. Saving sensitive information like this in plain text is always a very bad idea.

Related

Trying to write files on multiple lines

i am trying to have variables linked to together like this: (login,pass,name) i want to have several line of those but whenever i register it clears the file help would be appreciated thanks.
Private Sub btn_register_Click(sender As Object, e As EventArgs) Handles btn_register.Click
Dim newline As String
Dim anything As String
password = txt_passwordregister.Text
username = txt_usernameregister.Text
If password <> "" And username <> "" Then
If validatepass() = False Then
MsgBox("please enter more than 8 characters")
Else
newline = txt_usernameregister.Text & "," & txt_passwordregister.Text
If rad_student.Checked Then
anything = newline & "," & txt_fullname.Text
Student.WriteLine(anything)
Student.Close()
Else
End If
MsgBox("You are now registered!")
End If
End If
End Sub
You might want to specify what kind of file you are talking to.
but since you don't actually indicate something in particular, here i used StreamWriter to append lines of text to a file.
Using studentWriter As StreamWriter = New StreamWriter("(<path>\<filename>.<txt>)", True)
studentWriter.WriteLine(anything)
End Using
sorry for my bad english.
You didnt show what's happening with the object Student before..
We assume you are using StreamWriter here??
Our best guess is that you open the file in new file mode rather than append mode..
To enable Append mode, provide the parameter when you create the Student object like this :
Dim Student as New StreamWriter("[File Location]",[Append Mode])
When [Append Mode] is True it will append the file and write after the last line you've written into it before.
When [Append Mode] is False it will treat the file as a new file and all the content inside will be lost.

Compare each line in a text file with text in Text/Combo box

I need to be able to compare each line of a text file with the text a user has typed in a Text or Combo Box for serial key check and blocking certain website. At the moment, the blocked content is inside the programs code itself.
If ComboBox1.Text = "website.com" Then
WB.DocumentText = My.Settings.BlockedPage
ComboBox1.Text = "Blocked"
Else
WB.Navigate(Me.ComboBox1.Text)
ComboBox1.Items.Add(ComboBox1.Text)
End If
I find this way to be annoying as it would increase the file size of the compiled executable and stop me from updating it without releasing a whole new executable.
I have used this approach in another program, but I am sure the code I have used would compare it to the whole text file and not a line.
Dim key As String
key = My.Computer.FileSystem.ReadAllText("key.txt")
If TextBox1.Text = key Then
'Do functions, such as create licence file
Me.Close()
Else
MsgBox("Incorrect key", MsgBoxStyle.Exclamation, "Key Check")
End If
Would I just be able to modify that code to allow me to do what I want?
Thanks.
Try
If ComboBox1.Text.Equals("website.com") Then
WB.DocumentText = My.Settings.BlockedPage
ComboBox1.Text = "Blocked"
Else
WB.Navigate(Me.ComboBox1.Text)
ComboBox1.Items.Add(ComboBox1.Text)
End If
or
If ComboBox1.Text.Contains("website.com") Then
WB.DocumentText = My.Settings.BlockedPage
ComboBox1.Text = "Blocked"
Else
WB.Navigate(Me.ComboBox1.Text)
ComboBox1.Items.Add(ComboBox1.Text)
End If
use .Equal() or .Contains(). Try using .contain() when your trying to compare with a .txt file
Here is a way of doing that:
Dim lines = System.IO.File.ReadAllLines("File path")
Dim text As String
For i = 0 To lines.Length - 1
text = lines(i).ToString
If text = "Your serial here" Then
MsgBox("Serial found")
else
Msgbox("Serial not found")
End If
Next
This code you can use for the webbrowser:
Dim lines = System.IO.File.ReadAllLines(Application.StartupPath + "file path")
Dim text As String
For i = 0 To lines.Length - 1
text = lines(i).ToString
If WebBrowser1.Url.ToString.Contains(text) Then
WebBrowser1.Navigate("")
End If
Next
The text in the textfile should be in the format of:
www.website.com

Vb.net checkbox won't load from text file

I attempted to load a checkbox from a text file in VB.NET as a part of the settings form for my application. I used this piece of code:
Sub loadfiles()
Dim read As System.IO.StreamReader
read = My.Computer.FileSystem.OpenTextFileReader("C:\Users\Public\Documents\procrastinGONEnotif.txt")
Dim text As String = read.ReadToEnd()
read.Close()
If text = "false" Then
CheckBox1.Checked = False
Else
If text = "true" Then
CheckBox1.Checked = True
Else
MessageBox.Show("ERROR!")
End If
End If
End Sub
The file saving code is right here:
Dim write As System.IO.StreamWriter
write = My.Computer.FileSystem.OpenTextFileWriter("C:\Users\Public\Documents\procrastinGONEnotif.txt", False)
If CheckBox1.Checked = True Then
write.WriteLine("true")
Else
write.WriteLine("false")
End If
write.Close()
The file is supposed to load when the form starts and save when I press a button. However, the form does not load the file even though it is present and contains "true" or "false". Instead, the code detects it as "neither true or false" and sends the message "ERROR!", which I added to the application to test if it actually read the file.
The issue is when you read/write the value false. There is a newline character after false in the output file, which is visible when you open the text file or initially read it into text. An easy solution to this is to simply use read.ReadToEnd().Trim() to remove the extra whitespace characters.
You can also combine your nested If...Else into If...ElseIf...Else to make your code less confusing.
Sub loadfiles()
Dim read As System.IO.StreamReader
read = My.Computer.FileSystem.OpenTextFileReader("C:\Users\Public\Documents\procrastinGONEnotif.txt")
Dim text As String = read.ReadToEnd().Trim()
read.Close()
If text = "false" Then
CheckBox1.Checked = False
ElseIf text = "true" Then
CheckBox1.Checked = True
Else
MessageBox.Show("ERROR!")
End If
End Sub
You can shorten your entire code to this
For loading:
CheckBox1.Checked = Convert.ToBoolean(System.IO.File.ReadAllText("FILE_PATH"))
For saving
IO.File.WriteAllText("FILE_PATH", Convert.ToString(CheckBox1.Checked))

Highlight all lines that contain "admin" in a richtextbox

I am Making a chat for my Game launcher, when you launch it up theres a button that Opens a Chat Forum with a richtextbox on it that it refreshes/timer checks when the text has changed in the txt file on the server has changed from textbox1 then it will reprint the text but thats not the problem, i have an admin panel for it, but i want to highlight lines where there is "!ADMINISTRATOR!" in it so it shows the user is an admin and it highlighted to show what he is saying. i've tried this
Dim index As Integer = Me.RichTextBox1.Find("!ADMINISTRATOR!")
If index <> -1 Then
Dim lineindex As Integer = Me.RichTextBox1.GetLineFromCharIndex(index)
Dim first As Integer = Me.RichTextBox1.GetFirstCharIndexFromLine(lineindex)
Dim last As Integer = Me.RichTextBox1.GetFirstCharIndexFromLine(lineindex + 1)
If last = -1 Then last = Me.RichTextBox1.TextLength
Me.RichTextBox1.Select(first, last - first)
Me.RichTextBox1.SelectionBackColor = Color.Yellow
End If
But that works, in a way, it does not always highlight it, while it will highlight sometimes, it also may highlight the text a just just put, but that i don't mind, the main problem is that it only highlights the First line with the text in it, so if the admin posts a message on it it will highlight <3 but then a user will chat and then admin posts another message, it only highlights the first line that contains that text. if you need any more info oh and for testing purposes im using a local file on my pc, ive tested the ftp it works, but just to save time im using a txt file this is the code i use for the timer
Private Sub Timer1_Tick(sender As System.Object, e As System.EventArgs) Handles Timer1.Tick
If (System.IO.File.ReadAllText(Get_Directory_Current() & "\FilesDB\Chat\Chat.txt") = RichTextBox1.Text) Then
Else
Try
RichTextBox1.Text = System.IO.File.ReadAllText(Get_Directory_Current() & "\FilesDB\Chat\Chat.txt")
RichTextBox1.SelectionStart = RichTextBox1.Text.Length
RichTextBox1.ScrollToCaret()
ColorChat() ' this is the color chat that kinda dont work
Catch ex As Exception
End Try
End If
End Sub
if you can help thanks :) but for now i'm just trying new things. i guess it would kinda work a bit like syntax highlighting if you make it highlight a line instead of word.
Oh and if you wanted to know this is how i add the text to the chat / formatting
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
RichTextBox1.AppendText("<[" & Get_Time() & " " & strDate & "] " & "!ADMINISTRATOR!" & " | " & Environment.UserName & "> " & TextBox3.Text & vbNewLine)
End Sub
Use String.Replace() to inject the Rtf formatting where your target string appears.
Dim stringToFind = "!ADMINISTRATOR!"
Dim txt = Me.RichTextBox1.Text
Dim sb = New System.Text.StringBuilder()
sb.Append("{\rtf1\ansi\deff0 {\colortbl;\red0\green0\blue0;\red255\green0\blue0;}")
sb.Append(txt.Replace(stringToFind, String.Format("\cf2{0}\cf1", stringToFind)))
sb.Append("}")
Me.RichTextBox1.Rtf = sb.ToString()

Inputbox input to streamwriter file

So, in my assignment, we're supposed to create phone directories in the Directories.txt file and then change the listings in the directories. I made a blank directories.txt file and placed that in the debug folder. I also have created a button titled Create a New Phone Directory. When a user clicks on it, the inputbox shows up prompting the user to title the new directory. I am wondering how to get the results from that inputbox that the user typed and use that to create a new directory file in directories.txt and display it in a listbox. I think I have to use stream writer but every time I try, the result in the listbox shows up as system.IO.streamwriter.
This is my current code:
Private Sub btnCreate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreate.Click
inputDirectories = InputBox("Please Enter the Name of the New Directory")
If inputDirectories Is "" Then
MessageBox.Show("Invalid Directory Name")
End If
Dim fileDirectories As IO.StreamWriter = IO.File.CreateText(inputDirectories)
fileDirectories.WriteLine(inputDirectories)
End Sub
The assignment instructions say to use to write line method to add the name of the new file to the directories.txt file but I am totally lost on how to do this.
Any help would be appreciated!
Private Sub btnCreate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreate.Click
'
Dim path As String = "c:\temp\MyTestDirectory.txt"
Dim fileDirectories As System.IO.StreamWriter
Dim inputDirectory As String = ""
'
inputDirectory = InputBox("Please Enter the Name of the New Directory")
If inputDirectory = "" Then
MessageBox.Show("Invalid Directory Name")
Else
If System.IO.File.Exists(path) = False Then
'The file does not exist so create a new file & add the inputted data
fileDirectories = System.IO.File.CreateText(path)
fileDirectories.WriteLine(inputDirectory)
fileDirectories.Flush()
fileDirectories.Close()
Else
'The file exists so append file with the inputted data
fileDirectories = System.IO.File.AppendText(path)
fileDirectories.WriteLine(inputDirectory)
fileDirectories.Flush()
fileDirectories.Close()
End If
End If
'
End Sub
Sub ReadDataBackNow()
' Open the file to read from one line at a time
Dim path As String = "c:\temp\MyTestDirectory.txt"
Dim DataStreamIn As System.IO.StreamReader = System.IO.File.OpenText(path)
Dim TextLines As String = ""
'
Do While DataStreamIn.Peek() >= 0
TextLines = TextLines & DataStreamIn.ReadLine()
Loop
DataStreamIn.Close()
MsgBox(TextLines)
End Sub
UPDATE
Update to answer additional question.
In your button click event add the following line
Listbox1.Items.Add(inputDirectory)
Add the line AFTER the inner IF THEN block so your code would like this
If System.IO.File.Exists(path) = False Then
'The file does not exist so create a new file & add the inputted data
fileDirectories = System.IO.File.CreateText(path)
fileDirectories.WriteLine(inputDirectory)
fileDirectories.Flush()
fileDirectories.Close()
Else
'The file exists so append file with the inputted data
fileDirectories = System.IO.File.AppendText(path)
fileDirectories.WriteLine(inputDirectory)
fileDirectories.Flush()
fileDirectories.Close()
End If
Listbox1.Items.Add(inputDirectory)
Note that you will need several files to answer your question, so you may end up with something like
Directories.txt (contains list of directories)
Friends_Directory.txt
Workmates_Directory.txt
Family_Directory.txt
Friends_Directory.txt (contains list of friends)
Bob 1234567890
Angela 2345678901
Steve 3456789012
Ahmed 4567890123
Fatima 5678901234
Workmates_Directory.txt (contains list of workmates)
CEO_Alan 0987654321
Manager_Daisy 0876543219
Foreman_Judy 0765432198
Colleague_Jill 0654321987
Family_Directory.txt
Bro_Malcolm 1122334455
Sis_Alisha 2233445566
Moms 3344556677
Pops 4455667788
Uncle_Ben 5566778899
Aunty_Sarah 6677889900