Vb.net checkbox won't load from text file - vb.net

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

Related

Saving a Structure to a Binary File

I am creating an application using a windows forms application in visual studio in the vb.net language. I need help converting a structure that I coded into a binary file that is essentially a save in user results. I'm not a very good coder so excuse the poor code.
The code below shows that I have created a structure called saveresults and by clicking button1, it should get the contents of the binary file and edit them to be the new result. When I run the code the problem seems to be in the line FileOpen(1, "/bin/debug/1.txt", OpenMode.Binary) in the saveres subroutine.
Structure saveresults 'Structure for saving results
Dim numright As Integer
Dim numwrong As Integer
Dim totalnum As Integer
End Structure
'Subroutine aimed at getting stats saved to a text file to eventually be displayed to the user
Sub saveres(saveresults As saveresults, correct As Boolean)
saveresults.totalnum = saveresults.totalnum + 1
'Determining the contents to be saved to the binary file
If correct = True Then
saveresults.numright = saveresults.numright + 1
ElseIf correct = False Then
saveresults.numwrong = saveresults.numwrong + 1
End If
FileOpen(1, "/bin/debug/1.txt", OpenMode.Binary)
FilePut(1, saveresults)
FileClose(1)
End Sub
'attempt at saving results to the binary file
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim correct = True
Dim results As saveresults
FileOpen(1, "/bin/debug/1.txt", OpenMode.Binary)
FileGet(1, results)
saveres(results, correct)
FileClose(1)
End Sub
Any help would be appreciated. Thank you.
Use this instead
FileOpen(1, "1.txt", OpenMode.Binary)
Using the above opens the file in your project's debug folder.
You are referring to text files and binary files as if they are the same thing. They are not. Text files are human readable in Notepad; binary files are not.
I have not used the methods you are attempting since VB 6. Use the .Net System.IO methods. To use these you need to add Imports System.IO at the very top of your code file.
I have broken your code into Subs and Functions that have a single purpose. Reading the file, writing the file, updating the data, and displaying the data. This makes code more maintainable. If your code misbehaves it is easier to find the error and easier to fix if a method has only one thing to do.
The file location in the example is in the same directory as your .exe file. Probably
/bin/Degug.
'A Form level variable to hold the data
Private results As New saveresults
Structure saveresults 'Structure for saving results
Dim numright As Integer
Dim numwrong As Integer
Dim totalnum As Integer
End Structure
'Update the data
Private Sub UpdateResults(Correct As Boolean)
'It is not necessary to include = True when testing a Boolean
If Correct Then
'this is a shortcut method of writin results.numright = results.numright + 1
results.numright += 1
'A Boolean can only be True or False so if it is not True
'it must be False so, we can just use an Else
'No need to check the condition again
Else
results.numwrong += 1
End If
results.totalnum += 1
End Sub
'Write text file
Private Sub SaveResultsFile(results As saveresults, correct As Boolean)
Dim sb As New StringBuilder
sb.AppendLine(results.numright.ToString)
sb.AppendLine(results.numwrong.ToString)
sb.AppendLine(results.totalnum.ToString)
File.WriteAllText("1.txt", sb.ToString)
End Sub
'Read the text file
Private Function ReadResultsFile() As saveresults
Dim ResultsFiLe() = File.ReadAllLines("1.txt")
Dim results As New saveresults With
{
.numright = CInt(ResultsFiLe(0)),
.numwrong = CInt(ResultsFiLe(1)),
.totalnum = CInt(ResultsFiLe(2))
}
Return results
End Function
'Display
Private Sub DisplayResults()
Dim ResultsToDisplay As saveresults = ReadResultsFile()
'The $ indicates an interpolated string, the same thing can be accomplished with String.Format
Label1.Text = $"The correct number is {ResultsToDisplay.numright}. The wrong number is {ResultsToDisplay.numwrong}. The total is {ResultsToDisplay.totalnum}."
End Sub

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.

Writing Part/Block of File to another File

Please Help: I would like to read one block from file inPath and write to another file outPath.
I am using ReadLines method to read the File line by line and when reach at START_BLOCK, start writing to the output file and continue until you find the END_BLOCK.
I know couple of other methods by copying the whole file into a variable and pick the block what I need. I can't use saving on a variable as my files are very big GB+
The coding I have below copies the line at the "START_BLOCK" Can't really figure it out how to continue writing until the "END_BLOCK". Please suggest and thank you very much in advance.
Dim inPath As String = "C:\temprm\myFile.txt"
Dim outPath As String = "C:\temprm\myFileNew1.txt"
Using sw As StreamWriter = File.CreateText(outPath)
For Each line As String In File.ReadLines(inPath)
If line.Contains("START_BLOCK") Then
sw.WriteLine(line)
'-------HOW DO I CONTINUE TO WRITE UNTIL "END_BLOCK"
End If
Next line
End Using
You could just set a flag to indicate that you are inside of the block, and use that to write out the lines until you find the end tag, e.g. something like this (untested code!):
Dim inPath As String = "C:\temprm\myFile.txt"
Dim outPath As String = "C:\temprm\myFileNew1.txt"
Dim insideBlock As Boolean = False
Using sw As StreamWriter = File.CreateText(outPath)
For Each line As String In File.ReadLines(inPath)
If line.Contains("START_BLOCK") Then
sw.WriteLine(line)
insideBlock = True
ElseIf line.Contains("END_BLOCK") Then
sw.WriteLine(line)
insideBlock = False
Exit For
ElseIf insideBlock Then
sw.WriteLine(line)
End If
Next line
End Using
UPDATE
Since the comments are getting out of control - here's a version to handle multiple blocks with different start tags but the same end tag (untested since I'm at home on my Mac):
Dim inPath As String = "C:\temprm\myFile.txt"
Dim outPath As String = "C:\temprm\myFileNew1.txt"
Dim insideBlock As Boolean = False
Using sw As StreamWriter = File.CreateText(outPath)
For Each line As String In File.ReadLines(inPath)
If IsStartOfBlock(line) Then
sw.WriteLine(line)
insideBlock = True
ElseIf line.Contains("END_BLOCK") Then
sw.WriteLine(line)
insideBlock = False
ElseIf insideBlock Then
sw.WriteLine(line)
End If
Next line
End Using
'...
' Logic to determine if the line is the start of a block, for example:
Private Function IsStartOfBlock(line As String) As Boolean
Dim startMarkers() As String = {
"START_BLOCK", "START_BLOCK2", "START_BLOCKX"
}
Return startMarkers.Any(Function(x) line.Contains(x))
End Function
The loop will exit at the end of file anyway, so the last block should be ok too.

Reading TXT file line by line (VB 2010)

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.

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