I want to output specific line from text file but I don't know how - vb.net

So basically I'm making a library book record thing that tracks new books,view title and author.Right now, I'm in the stage of viewing all title and author in alphabetical order and I made them stored in a text file. My teacher suggested me to use bubble sort for sorting in alphabetical but right now I need more indepth explanation. Please help a man out thanks :D
Oh and the text file goes like this(no space in between except the last one using &vbcrlf):
Title
Author
Date published
Pagenum
ISBN
Sub Main()
'Making a book using the attributes and methods
Dim title As String = ""
Dim datepublished As Date = #01/01/0001# ' date is in month/day/year
Dim pagenum As Integer = 0
Dim isbn As String = ""
Dim author As String = ""
Dim amountbooks As Integer = 0
Dim choice As String = ""
'Declaring an object variable 'filename' which shows the file name (bookrecords.txt) and the path given
Dim filename As String = "C:\Users\Local_PC\Desktop\Try_oop_book\bookrecords.txt"
'Making a menu for the client
' A While loop for the menu that checks the user's input
While choice <> "1" AndAlso choice <> "2" AndAlso choice <> "3" AndAlso choice <> "4"
Console.Clear()
Console.WriteLine("----------LIBRARY MENU----------")
Console.WriteLine("[ 1 ]" & "Add New Book(s)")
Console.WriteLine("[ 2 ]" & "View all Book Titles")
Console.WriteLine("[ 3 ]" & "View all Authors")
Console.WriteLine("[ 4 ]" & "Exit")
Console.WriteLine(" ")
Console.Write("Pick a Menu Number: ")
choice = Console.ReadLine()
If choice <> "1" And choice <> "2" And choice <> "3" And choice <> "4" Then
Console.WriteLine("Please type in a valid input next time, press enter to retry again.")
Console.ReadLine()
Else
'Using choice, it goes to check which menu the user typed in.
If choice = "1" Then
'The user has chosen 1 which is to add new book(s) to the menu system.
'Setting the title of the book using mybook.setTitle
Console.WriteLine("How many books do you want to add?")
amountbooks = Console.ReadLine()
Dim bookarr(amountbooks) As Book 'This will initialise after amountbooks has been entered. Prevents from getting invalid index number of 0.
For x = 1 To amountbooks ' This loop will go over how many amount of books the user wants to add in to.
bookarr(x) = New Book()
Console.WriteLine("What is the title of the book?")
title = Console.ReadLine() 'This gives the value to store inside the variable 'title'
bookarr(x).setTitle(title) 'This line will set that 'title' into array bookarr
Console.WriteLine("Who is the author of the book?")
author = Console.ReadLine()
bookarr(x).setAuthor(author)
Console.WriteLine("When is the book published?")
datepublished = Console.ReadLine()
bookarr(x).setDatePublished(datepublished)
Console.WriteLine("How many page numbers are there?")
pagenum = Console.ReadLine()
bookarr(x).setPageNum(pagenum)
Console.WriteLine("What is the ISBN(code) of the book?")
isbn = Console.ReadLine()
bookarr(x).setISBN(isbn)
Console.Clear() 'clears everything after it has been written into a file
If System.IO.File.Exists(filename) = True Then
' Setting up an object variable for the streamwriter (which is the path folder and its name).
Dim objwriter As New System.IO.StreamWriter(filename, True) ' Has been set to true because the file exists and this will append(ADD) for the next str.
' if a file doesn't exists, it should be false which will ensure that a text file is created first.
objwriter.WriteLine(bookarr(x).getTitle & vbCrLf & bookarr(x).getAuthor & vbCrLf & bookarr(x).getDatePublished & vbCrLf & bookarr(x).getPageNum & vbCrLf & bookarr(x).getISBN & vbCrLf)
objwriter.Close() ' Closes the pathway to filename.
MsgBox("TEXT HAS BEEN SUCCESSFULLY REGISTERED")
Else
MsgBox("FILE DOES NOT EXIST")
End If
Next x
Else
If choice = "2" Then 'View all book titles
Dim readall As String = ""
Dim readtitle As String = ""
If System.IO.File.Exists(filename) = True Then
Dim objreader As New System.IO.StreamReader(filename)
readtitle = objreader.ReadLine
objreader.Close() 'Closes the pathway to filename
Console.WriteLine(readtitle) 'Outputs the all book title in alphabetical
Else
MsgBox("FILE DOES NOT EXIST")
End If
Console.ReadLine()
Else
If choice = "3" Then
Dim readauthor As String
Dim amountauthor As Integer = 0
Dim objreader As New System.IO.StreamReader(filename)
Else
Environment.Exit(0) 'idk I found this online :P but it works for exiting the console
End If
Console.ReadLine()
End If
End If
End If
End While
End Sub

Related

Checks The Informations In Text File. VB.NET

I work on a project "SignInLogeIn" using Visual Basic.NET.
I save the user informations in text file.
the name of the file is "data.txt".
to create a new account in my program. you must enter the name,email,password and the program write the informations in textfile.
i use "Streamwritter" to write the informations.
when user create a new account The program checks if the email entered by the user is already in the text file that contains the users' information.
and the program checks from informations by "StreamReader". it reads the information in text file and checks.
I have the problem.
when I CREATE A new account. problem appears.
and the problem is
"
An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll
Additional information: The process cannot access the file 'D:\1- Anas Files\Projects\VisualBasic.NET\SignInLogIn\SignInLogIn\SignInLogIn\bin\Debug\Data.txt' because it is being used by another process.
"
I think the problem is that I used the file twice
Once to write and once to read.
The error occurs in this line "Dim sw As New StreamWriter("Data.txt")".
how can i solve this problem ?
this is the code of "SignIn" button
Private Sub btnSignIn_Click(sender As Object, e As EventArgs) Handles btnSignIn.Click
Dim strEmail As String = txtEmail.Text
Dim Reg As New Regex("^\w+([-_.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$")
If txtUserName.Text.Trim() = "" Or txtEmail.Text.Trim() = "" Or txtPassword.Text.Trim() = "" Then
MsgBox("Please Enter All Input")
If Not Reg.IsMatch(strEmail) Then
MsgBox("Please Enter Email")
End If
Else
Dim sr As New StreamReader("Data.txt")
Dim sw As New StreamWriter("Data.txt")
Dim strPerson As String = txtUserName.Text & ";" & txtEmail.Text & ";" & txtPassword.Text
Dim line As String = ""
Do
line = sr.ReadLine()
Dim arrData As String() = line.Split(";")
If arrData(1) = strEmail Then
MsgBox("Please Change Email")
Else
sw.WriteLine(strPerson)
sw.Close()
End If
Loop While line <> Nothing
sr.Close()
End If
End Sub
You open twice the same file. First, to read and second to write, this is why you cannot write.
Dim sr As New StreamReader("Data.txt")
Dim lines As String = sr.ReadToEnd().Split(Environment.NewLine)
sr.Close()
Dim strPerson As String = txtUserName.Text & ";" & txtEmail.Text & ";" & txtPassword.Text
Dim sw As New StreamWriter("Data.txt")
For Each line As String In lines
Dim arrData As String() = line.Split(";")
If arrData(1) = strEmail Then
MsgBox("Please Change Email")
Exit For
Else
sw.WriteLine(strPerson)
Exit For
End If
Next
sw.Close()
Streams need to be closed and disposed. They are usually put in Using blocks.
I wasn't quite sure of the program flow you wanted. It seemed, since you created a writer and a reader you intended to add to user to the file if they were not listed.
I broke out some of the code into separate methods. I used System.IO since we have a simple text file.
Private Sub btnSignIn_Click(sender As Object, e As EventArgs) Handles btnSignIn.Click
If ValidInput() Then
Dim strPerson As String = $"{txtUserName.Text};{txtEmail.Text};{txtPassword.Text}"
If Not IsUserInFile(strPerson) Then
File.AppendAllText("Data.txt", strPerson & Environment.NewLine)
End If
End If
End Sub
Private Function ValidInput() As Boolean
Dim strEmail As String = txtEmail.Text
Dim Reg As New Regex("^\w+([-_.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$")
If txtUserName.Text.Trim() = "" OrElse txtEmail.Text.Trim() = "" OrElse txtPassword.Text.Trim() = "" Then
MsgBox("Please Enter All Input")
Return False
If Not Reg.IsMatch(strEmail) Then
MsgBox("Please Enter Email")
Return False
End If
End If
Return True
End Function
Private Function IsUserInFile(Person As String) As Boolean
Dim p = Person.Split(";"c)
Dim lines = File.ReadAllLines("Data.txt")
For Each line In lines
If Person = line Then
Return True
End If
Dim fields = line.Split(";"c)
If fields(0) = p(0) AndAlso fields(2) = p(2) AndAlso fields(1) <> p(1) Then
MessageBox.Show("Please Change Email")
Return False
End If
Next
Return False
End Function
This is going to get messy and slow if there are too many users. This info should really be in a database. The worst thing is the passwords should always be salted and hashed; never stored as plain text even is a database.

Comparing text in two Richtextboxes and get the differences

I'm want to compare the text between two richtextboxes and get the differences in the third one. Without highlight the text.
So far, the best option is this solution
The first solution works, but it doesn't remove the text present in richtextbox2 from the richtextbox1.
Endeed, the user asked
if they are the same do nothing.
My case is complete the opposite and still i cannot find a solution.
Thanks
First, you need to add a combobox to your form named (combobox1)
then add these items in it:
RichTextbox1 - RichTextbox2
RichTextbox2 - RichTextbox1
second, add a button named (button1), under this button click event
insert this code:
RichTextBox3.Clear()
If RichTextBox1.Text <> "" And RichTextBox2.Text <> "" And RichTextBox1.Text <> RichTextBox2.Text And ComboBox1.SelectedItem = "RichTextbox1 - RichTextbox2" Then
Dim txt1(RichTextBox1.Text.Split(" ").Length) As String
Dim txt2(RichTextBox2.Text.Split(" ").Length) As String
txt1 = RichTextBox1.Text.Split(" ")
txt2 = RichTextBox2.Text.Split(" ")
Dim diff1 As String = ""
For Each diff As String In txt1
If Array.IndexOf(txt2, diff.ToString) = -1 Then
diff1 += diff.ToString & " "
End If
Next
RichTextBox3.Text = diff1.ToString
End If
If RichTextBox1.Text <> "" And RichTextBox2.Text <> "" And RichTextBox1.Text <> RichTextBox2.Text And ComboBox1.SelectedItem = "RichTextbox2 - RichTextbox1" Then
Dim txt1(RichTextBox1.Text.Split(" ").Length) As String
Dim txt2(RichTextBox2.Text.Split(" ").Length) As String
txt1 = RichTextBox1.Text.Split(" ")
txt2 = RichTextBox2.Text.Split(" ")
Dim diff2 As String = ""
For Each diff As String In txt2
If Array.IndexOf(txt1, diff.ToString) = -1 Then
diff2 += diff.ToString & " "
End If
Next
RichTextBox3.Text = diff2.ToString
End If
now, you have 2 options:
if you choose (RichTextbox1 - RichTextbox2) from the combobox then click the button, richtextbox3 will display the text which is found in richtextbox1 and not found in richtextbox2, while if you choose (RichTextbox2 - RichTextbox1), the opposite will happen
finally, if the 2 richtextboxes is the same, nothing will occur
Also you could use String.Join *
Under Button1 click event replace this code with the previous one:
Dim intsA = RichTextBox1.Text.Split(" ")
Dim intsB = RichTextBox2.Text.Split(" ")
Dim myresult = intsA.Except(intsB).ToArray()
RichTextBox3.Text = String.Join(" ", myresult)
if you found this useful, mark it as answer

How to read from a file and search for the input of the user on the file? VB.NET

This my code i want to search for the input of the user i.e string on a certain .txt file and if it finds it displays date found else input not found.
Dim freader As IO.StreamReader
Dim strline, a As String
freader = New IO.StreamReader(" C:\Users\neWbie889\Documents\vb\strings.txt")
strline = freader.ReadLine
Do While Not strline Is Nothing
strline = freader.ReadLine()
Loop
Console.WriteLine("enter your string")
a = Console.ReadLine()
If strline = a Then
Console.WriteLine("input found")
ElseIf strline <> a Then
Console.WriteLine("input not found")
End If
freader.Close()
the text file consists of data in this order:
750401 234523
456465 345345
054156 34534
023156 534543
156456 435345
You can read all the text from the file into a string:
Dim allText As String = File.ReadAllText("path to file")
and then check for the string the user gave with Contains method:
If allText.Contains(a) = True Then
Console.WriteLine("input found")
Else
Console.WriteLine("input not found")
End If
Imports System.IO
Module Module1
Sub Main()
Dim a As String
Dim allText As String = File.ReadAllText("C:\Users\KronosXtitan\Documents\vb\ddates.txt")
Console.WriteLine("enter a number")
a = Console.ReadLine()
If allText.Contains(a) = True Then
Console.WriteLine("the number was found")
Else
Console.WriteLine("the number was not found")
End If
End Sub
End Module
thanks to γηράσκω δ' αεί πολλά διδασκόμε for helping me solve this

Saving data with a file name of my choice

Very kindly, an intelligent member of stack overflow showed me how to loop with 'Do Until' and generate messages boxes to enable a user to save a file or rename one, if it already exists. However, I'm still hitting a wall. I can't save the ListView data in my for loop, with the file name I have chosen in the Input Box (see code below). Its like I have two separate pieces of code because rtb is saving data in a Rich Text File called Test.txt and saveFile has nothing to do with this! Please help
Code
Dim fileSaved As Boolean
Do Until fileSaved
Dim saveFile As String = InputBox("Enter a file name to save this message")
If saveFile = "" Then Exit Sub
Dim docs As String = My.Computer.FileSystem.SpecialDirectories.MyDocuments
Dim filePath As String = IO.Path.Combine(docs, "Visual Studio 2013\Projects", saveFile & ".txt")
fileSaved = True
If My.Computer.FileSystem.FileExists(filePath) Then
Dim msg As String = "File Already Exists. Do You Wish To Overwrite it?"
Dim style As MsgBoxStyle = MsgBoxStyle.YesNo Or MsgBoxStyle.DefaultButton2 Or MsgBoxStyle.Critical
fileSaved = (MsgBox(msg, style, "Warning") = MsgBoxResult.Yes)
End If
Loop
'THIS NEXT bit of code saves content to Test.txt NOT saveFile as desired!
Dim rtb As New RichTextBox
rtb.AppendText("Generation, Num Of Juveniles, Num of Adults, Num of Semiles, Total" & vbNewLine)
For Each saveitem As ListViewItem In ListView1.Items
rtb.AppendText(
saveitem.Text & ", " &
saveitem.SubItems(1).Text & ", " &
saveitem.SubItems(2).Text & ", " &
saveitem.SubItems(3).Text & ", " &
saveitem.SubItems(4).Text & vbNewLine)
Next
rtb.SaveFile("C:\Users\SMITH\Documents\Visual Studio 2013\Projects\Test.txt", _
RichTextBoxStreamType.PlainText)
When you try to save the file with the RichTextBox method SaveFile you need to be able to use the variable filePath that receive the input from your user. But this variable is declared inside the block Do Until .... Loop and according to scope rules of variables in VB.NET is not available outside that block. You could move the declaration of the variable before entering the loop
Dim fileSaved As Boolean
Dim filePath As String
Do Until fileSaved
Dim saveFile As String = InputBox("Enter a file name to save this message")
If saveFile = "" Then Exit Sub
Dim docs as String = My.Computer.FileSystem.SpecialDirectories.MyDocuments
filePath = IO.Path.Combine(docs, "Visual Studio 2013\Projects", saveFile & ".txt")
fileSaved = True
If My.Computer.FileSystem.FileExists(filePath) Then
Dim msg As String = "File Already Exists. Do You Wish To Overwrite it?"
Dim style As MsgBoxStyle = MsgBoxStyle.YesNo Or MsgBoxStyle.DefaultButton2 Or MsgBoxStyle.Critical
fileSaved = (MsgBox(msg, style, "Warning") = MsgBoxResult.Yes)
End If
Loop
' The remainder of your code can be left unchanged until the SaveFile line
Now you could use it in the call
rtb.SaveFile(filePath, RichTextBoxStreamType.PlainText)

Vb.net Journal Program Issue

Okay so for an internship project i'm making a Journal with streamwriters and streamreaders.
I have to to where you can create an account with a name, Username, and Password. I also have it to where it creates a txt file in that persons name when you create the account. Now, they login and it brings them to the journal page. The Journal Page for the most part has a Date for your journal Entry, the title of the journal and the journal entry text itself.
The problem that I am having is that when you click the button to create/edit a journal entry, it goes through a sub routine that checks if that journal exists (Meaning that there is already one for that date) or not. If it doesn't exist, then it should create a new one at the bottom of the text file. If it does exist then it should edit the lines in which that journal are stationed in the text file.
Code:
Private Sub CreateBtn_Click(sender As System.Object, e As System.EventArgs) Handles CreateBtn.Click
Errors = ""
Dim TempCounter As Integer = 0
If TitleTxt.Text = "" Then
Errors = "You must enter a title." & vbCrLf
End If
If JournalTextRtxt.Text = "" Then
Errors &= "You must enter an entry for the journal."
End If
If Errors <> "" Then
MessageBox.Show("There's an error in creating/editing your journal." & vbCrLf & "Error(s):" & vbCrLf & Errors, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
JournalDate = DateTimePicker1.Value
JournalTitle = TitleTxt.Text
JournalText = JournalTextRtxt.Text
arrJournalEntries(TempCounter).TheDate = JournalDate
arrJournalEntries(TempCounter).Title = JournalTitle
arrJournalEntries(TempCounter).JournalEntry = JournalText
CheckAndWrite()
End If
End Sub
Private Sub CheckAndWrite()
Dim Reader As New StreamReader(MyName & ".txt", False)
Dim Sline As String = Reader.ReadLine
Counter = 0
Do Until (Sline Is Nothing) 'Perform the code until the line in the text file is blank
If Not Sline Is Nothing Then 'If the line in the text file is NOT blank then
For i As Integer = 1 To 3
Select Case i
Case 1
arrJournalEntries(Counter).TheDate = Sline
Sline = Reader.ReadLine
Case 2
arrJournalEntries(Counter).Title = Sline
Sline = Reader.ReadLine
Case 3
arrJournalEntries(Counter).JournalEntry = Sline
Sline = Reader.ReadLine
End Select
Next
End If
JournalDate = arrJournalEntries(Counter).TheDate
Time = DateTimePicker1.Value
MsgBox("Journal Date = " & JournalDate & vbCrLf & "Today's Date = " & Time)
If Time = JournalDate Then
JournalFound = True
Else
Counter += 1
JournalFound = False
End If
Loop
Reader.Close()
Try
If Sline Is Nothing Or JournalFound = False Then
MsgBox("Your journal is now going to be created.")
JournalDate = DateTimePicker1.Value
JournalTitle = TitleTxt.Text
JournalText = JournalTextRtxt.Text
arrJournalEntries(Counter).TheDate = JournalDate
arrJournalEntries(Counter).Title = JournalTitle
arrJournalEntries(Counter).JournalEntry = JournalText
Dim Writer As New StreamWriter(MyName & ".txt", True)
Do Until (arrJournalEntries(Counter).TheDate = Nothing)
Writer.WriteLine(arrJournalEntries(Counter).TheDate)
Writer.WriteLine(arrJournalEntries(Counter).Title)
Writer.WriteLine(arrJournalEntries(Counter).JournalEntry)
Counter += 1
Loop
Writer.Close()
End If
If JournalFound = True Then
MsgBox("Your journal is now going to be edited.")
JournalDate = DateTimePicker1.Value
JournalTitle = TitleTxt.Text
JournalText = JournalTextRtxt.Text
arrJournalEntries(Counter).TheDate = JournalDate
arrJournalEntries(Counter).Title = JournalTitle
arrJournalEntries(Counter).JournalEntry = JournalText
Dim Writer As New StreamWriter(MyName & ".txt", True)
Do Until (arrJournalEntries(Counter).TheDate = Nothing)
Writer.WriteLine(arrJournalEntries(Counter).TheDate)
Writer.WriteLine(arrJournalEntries(Counter).Title)
Writer.WriteLine(arrJournalEntries(Counter).JournalEntry)
Counter += 1
Loop
Writer.Close()
End If
Catch ex As Exception
MessageBox.Show("An error has occured" & vbCrLf & vbCrLf & "Original Error:" & vbCrLf & ex.ToString)
End Try
End Sub`
The problem that's occuring is that it's not only writing in the first time wrong. When it's supposed to say it's going to edit, it doesn't, it just says creating. But it just adds on to the file. After pressing the button 3 times with the current date. and the Title being "Test title", and the journal entry text being "Test text". This is what occured.
It should just be
7/10/2012 3:52:08 PM
Test title
Test text
7/10/2012 3:52:08 PM
Test title
Test text
the whole way through. but of course if it's the same date then it just overwrites it. So can anybody please help me?
You are only filtering your array by the date, so it looks like you have an object with a date but no title or text:
Do Until (arrJournalEntries(Counter).TheDate = Nothing)
The "quick" fix:
Do Until (arrJournalEntries(Counter).TheDate = Nothing)
If arrJournalEntries(Counter).Title <> String.Empty Then
Writer.WriteLine(arrJournalEntries(Counter).TheDate)
Writer.WriteLine(arrJournalEntries(Counter).Title)
Writer.WriteLine(arrJournalEntries(Counter).JournalEntry)
End If
Counter += 1
Loop
Do consider getting rid of the array and using a List(of JournalEntry) instead. Your code looks difficult to maintain in its current state.