Search through text file and return a line of text - vb.net

I am trying to create a program that will search a text file for a line of text and then return the full line of information.
Example line: Joe Blogs JBL 1234
Search: Joe Blogs
Search returns: Joe Blogs JBL 1234
To make it as simple as possible, I have 2 text boxes & 1 button.
Textbox1 = search
Textbox2 = Search results
Button = Search button
Can anyone tell me how to do this because I'm finding it really difficult. I'm new to VB coding so the simplest of code would be helpful!
This is what I have so far:
Imports System.IO
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' Input Text Error
If TextBox1.TextLength = 0 Then
MsgBox("Please enter a Staff Name or Staff Code", MsgBoxStyle.Information, "Error")
End If
'Perform Search
Dim strText As String = SearchFile("F:\Documents\Documents\Visual Studio 2015\Projects\ExtentionLocator\ExtentionLocator\Extentionlist.txt", TextBox1.Text)
If strText <> String.Empty Then
TextBox2.Text = strText
End If
End Sub
'Search Function
Public Shared Function SearchFile(ByVal strFilePath As String, ByVal strSearchTerm As String) As String
Dim sr As StreamReader = New StreamReader(strFilePath)
Dim strLine As String = String.Empty
Try
Do While sr.Peek() >= 0
strLine = String.Empty
strLine = sr.ReadLine
If strLine.Contains(strSearchTerm) Then
sr.Close()
Exit Do
End If
Loop
Return strLine
Catch ex As Exception
Return String.Empty
End Try
End Function
'Clear Button
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
TextBox2.Text = ""
TextBox1.Text = ""
End Sub
' Open The text file
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Process.Start("C:\Users\kylesnelling\Documents\Visual Studio 2015\Projects\ExtentionLocator\ExtentionLocator\Extentionlist.txt")
End Sub
End Class
Whenever I perform a search, all I get back is the last line of the text file... does anyone know why?

As Alex B has stated in comments, line If strLine.Contains("textbox1.text") should be If strLine.Contains(strSearchTerm)
Also you are not passing in the search item to the function. The below line you have passed in the string textbox1.text as a string rather than the text inside the textbox. Hence why you never find the line you are searching for and always returns the last record of your file.
Dim strText As String = SearchFile("F:\Documents\Documents\Visual Studio 2015\Projects\ExtentionLocator\ExtentionLocator\Extentionlist.txt", "textbox1,text")
This line should be:
Dim strText As String = SearchFile("F:\Documents\Documents\Visual Studio 2015\Projects\ExtentionLocator\ExtentionLocator\Extentionlist.txt", textbox1.text)
Also with this line Dim sr As StreamReader = New StreamReader("F:\Documents\Documents\Visual Studio 2015\Projects\ExtentionLocator\ExtentionLocator\Extentionlist.txt") why have you used the same path destination when you have already passed in this file location in the variable strFilePath.
line should be Dim sr As StreamReader = New StreamReader(strFilePath)
Its best to use the variables being passed into the function otherwise this function won't be very useful to other parts of code that may be referencing it or if search terms or filepaths change.
Updated from comments:
strLine.ToUpper.Contains(strSearchTerm.ToUpper) this line will make both text uppercase and the word you are searching for to uppercase, which will allow them to ignore case sensitivity, so for example, "text" can match with "Text" by both being converted to "TEXT" when used to compare.

Give this a try friend.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim searchResult As String = SearchFile("F:\Documents\Documents\Visual Studio 2015\Projects\ExtentionLocator\ExtentionLocator\Extentionlist.txt", _
"text to search for")
Me.TextBox2.Text = searchResult
End Sub
Public Shared Function SearchFile(ByVal strFilePath As String, ByVal strSearchTerm As String) As String
Dim fs As New System.IO.StreamReader(strFilePath)
Dim currentLine As String = String.Empty
Try
Dim searchResult As String = String.Empty
Do While fs.EndOfStream = False
currentLine = fs.ReadLine
If currentLine.IndexOf(strSearchTerm) > -1 Then
searchResult = currentLine
Exit Do
End If
Loop
Return searchResult
Catch ex As Exception
Return String.Empty
End Try
End Function

Related

is there a way to combine strings into a working save / delete funtion

I am using two separate functions: one to save and one to delete. I would like to roll them into one function if possible even though VB gives me the wrong information. This is what I have so far:
Public Sub popup(sender As Object, e As EventArgs)
Dim ans As String
ans = MsgBox(Operation & name, vbYesNo + Type, tital)
If ans = vbYes Then
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Save.Click
'save
Dim name As New String = "NAME_HERE"
Dim Operation As New String = "Would you like to Save your Changes to "
Dim tital As New String = "save this record "
Dim Type As New String = vbQuestion
Call popup(e, e)
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Delete.Click
'delete
Dim name As New String = "NAME_HERE"
Dim Operation As String = "Would you like to Delete your Record "
Dim tital As New String = "Delete this record "
Dim Type As New String = vbExclamation
Call popup(e, e)
End Sub
Is the only way to roll it into one function to extend the ans = with strings like name2, Operation2, tital2, Type2 or is there a tidy solution?
Your popup is a subroutine but I think it should be a function. You want to act on the result of the MsgBox. Here's a function that returns what the user selected:
Public Function Popup(name As String, operation As String, title As String, style As MsgBoxStyle) As MsgBoxResult
Return MsgBox(operation & name, vbYesNo + style, title)
End Function
I've adjusted a few things in your code:
You cannot use New with String the way you are trying to (Dim name As New String = "NAME_HERE")
I made type into a MsgBoxStyle variable
Here's the updated code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Save.Click
'save
Dim name As String = "NAME_HERE"
Dim Operation As String = "Would you like to Save your Changes to "
Dim tital As String = "save this record "
Dim style As MsgBoxStyle = MsgBoxStyle.Question
Dim result As MsgBoxResult = Popup(name, Operation, tital, style)
Select Case result
Case MsgBoxResult.Yes
' Save changes
Case Else
End Select
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Delete.Click
'delete
Dim name As String = "NAME_HERE"
Dim Operation As String = "Would you like to Delete your Record "
Dim tital As String = "Delete this record "
Dim style As MsgBoxStyle = MsgBoxStyle.Exclamation
Dim result As MsgBoxResult = Popup(name, Operation, tital, style)
Select Case result
Case MsgBoxResult.Yes
' Delete record
Case Else
End Select
End Sub
There is no overload of constructors for a String that does not have parameters. .Net allows you declare a String directly.
vbExclamation and vbQuestion are not a strings.
I have no idea what you expect to get with Call popup(e, e) Why would you want to send the EventArgs for the button to your popup Sub? You declared a message and a title in the button event but these values are never passed to the popup Sub. Those variables are local to the the button event and not visible in the popup method. Even if they were available, why would you want to concatenate the
When you declare your own methods (like popup) you can determine what needs to be sent to the method so it can do its work. These are the parameters of the method. When you call the method you pass arguments that match the expected parameters. The values in these arguments can be used inside your method.
BTW, the Call keyword is not needed except in special circumstanse.
I would like to show you the .Net way to use MessageBox instead of the old VB6 way. If you start to code in C# you will be comfortable with MessageBox.
I used a Select Case so it would be easy to add other message boxes, for example an Update message box.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim RetVal = CustomMB("Delete")
If RetVal = DialogResult.Yes Then
'Code to delete
End If
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim RetVal = CustomMB("Save")
If RetVal = DialogResult.Yes Then
'Code to save
End If
End Sub
Private Function CustomMB(MBType As String) As DialogResult
Dim dr As New DialogResult()
Select Case MBType
Case "Delete"
dr = MessageBox.Show("Would you like to Delete your Record", "Delete this record ", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation)
Case "Save"
dr = MessageBox.Show("Would you like to Save your Changes to ", "save this record ", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
Case Else
dr = MessageBox.Show("Sorry, no matching message box was found")
End Select
Return dr
End Function

Variables are used before it is assigned a null value. Using StreamReader

I decided to try one of the advanced exercises in my book, it needs me to edit a program. Before getting the artist name and price, the btn.Add_Click procedure should determine whether the CD name is already included in the list box. If the list box contains the CD name, the procedure should display an appropriate message and then not add the CD to the list. Problem is the Do Until inFile.Peek = -1 and the For Each Name As String In strNameCollection apparently are assigned a null value. Any ideas on why this is or possibly how to get this to work? btn.Add_Click is towards the bottom of the code
Option Explicit On
Option Strict On
Option Infer Off
Public Class frmMain
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub
Private Sub frmMain_FormClosing(sender As Object, e As Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
' save the list box information
' declare a StreamWriter variable
Dim outFile As IO.StreamWriter
' open the file for output
outFile = IO.File.CreateText("CDs.txt")
' write each line in the list box
For intIndex As Integer = 0 To lstCds.Items.Count - 1
outFile.WriteLine(lstCds.Items(intIndex))
Next intIndex
' close the file
outFile.Close()
End Sub
Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles Me.Load
' fills the list box with data
' stored in a sequential access file
' declare variables
Dim inFile As IO.StreamReader
Dim strInfo As String
' verify that the file exists
If IO.File.Exists("CDs.txt") Then
' open the file for input
inFile = IO.File.OpenText("CDs.txt")
' process loop instructions until end of file
Do Until inFile.Peek = -1
strInfo = inFile.ReadLine
lstCds.Items.Add(strInfo)
Loop
inFile.Close()
' select the first line in the list box
lstCds.SelectedIndex = 0
Else
MessageBox.Show("Can't find the CDs.txt file",
"CD Collection",
MessageBoxButtons.OK,
MessageBoxIcon.Information)
End If
End Sub
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
' adds CD information to the list box
' declare variables
Dim strName As String
Dim strArtist As String
Dim strPrice As String
Dim strConcatenatedInfo As String
Dim dblPrice As Double
Dim strNameCollection() As String
'read all names into array
Dim inFile As IO.StreamReader
If IO.File.Exists("CDs.txt") Then
' open the file for input
inFile = IO.File.OpenText("CDs.txt")
End If
'read all names into array
Dim index As Integer = 0
Do Until inFile.Peek = -1
ReDim strNameCollection(index)
strNameCollection(index) = inFile.ReadLine
Loop
inFile.Close()
' get the CD information
strName = InputBox("CD name:", "CD Collection")
For Each Name As String In strNameCollection
If strName = Name Then
MessageBox.Show("Sorry that name was alread on the list", "CD Project",
MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
Else
strArtist = InputBox("Artist:", "CD Collection")
strPrice = InputBox("Price:", "CD Collection")
Double.TryParse(strPrice, dblPrice)
strPrice = dblPrice.ToString("N2")
strConcatenatedInfo = strName.PadRight(40) &
strArtist.PadRight(25) & strPrice.PadLeft(5)
lstCds.Items.Add(strConcatenatedInfo)
End If
Next Name
End Sub
Private Sub btnRemove_Click(sender As Object, e As EventArgs) Handles btnRemove.Click
' removes the selected line from the list box
' if a line is selected, remove the line
If lstCds.SelectedIndex <> -1 Then
lstCds.Items.RemoveAt(lstCds.SelectedIndex)
End If
End Sub
End Class
Why not take advantage of the Using blocks? Make strNameCollection a List(Of String) instead of an array that you are not increasing it's size correctly.
Private strNameCollection As New List(Of String)
Using sr As New StreamReader("CDs.txt")
While Not sr.EndOfStream
strNameCollection.Add(sr.ReadLine)
End while
End Using ' file closed and stream disposed

order by date in txt file using vb.net

i made a program that takes release date and title from IMDB api and saves them in them in .txt file...can i order them by date somehow
Imports System.IO
Imports System.Xml.Linq
Imports System.Text.RegularExpressions
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim _reg As Regex = New Regex("http://www.imdb.com/title/([A-Za-z0-9\-]+)/*?", _
RegexOptions.IgnoreCase)
Dim value As String = TextBox1.Text
Dim m As Match = _reg.Match(value)
If (m.Success) Then
Dim key As String = m.Groups(1).Value
Dim url As String = "http://mymovieapi.com/?id=" + key + "&type=xml&plot=none&episode=0&lang=en-US&aka=simple&release=simple&business=0&tech=0"
Dim Document As XDocument = XDocument.Load(url)
Dim title = Document.Root.Element("title").Value()
Dim releaseDate = Date.ParseExact(Document.Root.Element("release_date").Value,
"yyyyMMdd", System.Globalization.CultureInfo.InstalledUICulture)
TextBox2.Text = "Release Date: " & releaseDate & " / Title: " & title
Else : TextBox2.Text = "Please use IMDB links"
End If
Button2.Enabled = True
End Sub
Private Sub Button2_Click_1(sender As System.Object, e As System.EventArgs) Handles Button2.Click
Dim Writer As System.IO.StreamWriter
Writer = New System.IO.StreamWriter("C:\Users\Azer\Documents\Movies.txt", True)
Writer.Write(TextBox2.Text & vbCrLf)
Writer.Close()
Button2.Enabled = False
End Sub
Private Sub Button4_Click(sender As System.Object, e As System.EventArgs) Handles Button4.Click
Dim Reader As System.IO.StreamReader
Reader = New System.IO.StreamReader("C:\Users\Azer\Documents\Movies.txt")
Dim tempstring As String
Do
tempstring = Reader.ReadLine()
TextBox3.Text = TextBox3.Text + tempstring + vbCrLf
Loop Until tempstring = ""
Reader.Close()
End Sub
Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click
Me.Close()
End Sub
Private Sub Button5_Click(sender As System.Object, e As System.EventArgs) Handles Button5.Click
TextBox3.Clear()
End Sub
End Class
As David said, a database would make this a lot easier. However, if you can't use a database (or have some other reason for doing it this way), here's one way to approach it.
Make a small class that holds the information (to make it easier to sort, like this:
Public Class MovieInfo
Public Property As DateTime
Public Title As String
End Class
Next, read the current file (if it exists) and populate a List<MovieInfo> with the data in it.
Dim movies As String() = File.ReadAllLines("C:\Users\Azer\Documents\Movies.txt")
Dim movieParts = From m in movies
Select m.Split(New String() { "/", ":" }, StringSplitOptions.RemoveEmptyEntries)
Dim parsedDate As DateTime
Dim movieData As List(Of MovieInfo) = (From mi In movieParts
Select New MovieInfo With
{
.ReleaseDate = _
If(DateTime.TryParseExact(mi(1).Trim, "dd.MM.yyyy", _
System.Globalization.CultureInfo.InvariantCulture, _
System.Globalization.DateTimStyle.None, _
parsedDate), parsedDate, DateTime.MinValue),
.Title = mi(3).Trim()
}.ToList()
Essentially the code above reads the text file into an array (one line per element), and then using LINQ splits each line into 4 parts based on : and /. Then it takes the result of that query and builds a List of MovieInfo, with the date string converted to DateTime for easy sorting.
The DateTime.TryParseExact takes an input string of the specified format (in this case, dd.MM.yyyy) and if possible converts it to a DateTime object. If it's successful, it returns true and the DateTime value is in the parsedDate variable. If it's not true, I use the MinValue for DateTime for the ReleaseDate property of the MovieInfo class.
After that, you'll get the new data from your API call and add it to the List of MovieInfo (you'll probably want to eliminate any duplicates). Since you didn't post the format of the data from the API, it's rather hard for me to give you a code sample to parse it, but in a nutshell you can build a second list of MovieInfo objects and then merge the existing and new list together.
Then you sort the List of MovieInfo and overwrite the original text file. Something like this should do the trick:
movieData.Sort(Function(x, y) y.ReleaseDate.CompareTo(x.ReleaseDate))
Dim output As New StringBuilder()
For Each info As MovieInfo in movieData
output.Append("Release Date: ")
output.Append(info.ReleaseDate.ToString("dd.MM.yyyy"))
output.Append(" / Title: ")
output.Append(info.Title)
output.Append(Enviroment.NewLine)
Next
File.WriteAllText("C:\Users\Azer\Documents\Movies.txt", output.ToString())
This code sorts the list with a lambda expression to put the movies in date order (newest to oldest). It then uses a StringBuilder with a For Each loop to build the output, and then writes it to the file (overwriting the file if it already exists).
Note that if you reverse the x and the y in the Sort, you'll get oldest to newest by date.
Dim allLines As String() = File.ReadAllLines("your file name")
System.Array.Sort(allLines)
IO.File.WriteAllLines("your file name", allLines) 'assuming you want to write the file

How to read a specific line from a text file in VB

I am creating a program that is supposed to write text into a text file, and should be able to read specific lines from a text file in VB (so if i needed to read a specific name I could select line 5 and it would display in the textbox). I am able to read the text from the text file but I do not know how to control a specific line.
Here is my code:
Public Class Form1
Private Sub btnSubmit_Click(sender As System.Object, e As System.EventArgs) Handles btnSubmit.Click
Dim writer As New System.IO.StreamWriter("/text.txt", True)
writer.WriteLine(txtFirstName.Text)
writer.WriteLine(txtLastName.Text)
writer.WriteLine("-------------------------------------")
writer.Close()
End Sub
Private Sub btnRead_Click(sender As System.Object, e As System.EventArgs) Handles btnRead.Click
Dim reader As New System.IO.StreamReader("/text.txt")
Dim FirstName, LastName As String
FirstName = reader.ReadLine()
LastName = reader.ReadLine()
reader.Close()
txtFirstName.Text = FirstName
txtLastName.Text = LastName
End Sub
Private Sub btnClear_Click(sender As System.Object, e As System.EventArgs) Handles btnClear.Click
txtFirstName.Clear()
txtLastName.Clear()
End Sub
End Class
Any help would be appreciated. Thanks!
You will have to read all lines up to the one you're interested in. For example:
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
' Succeded!
Return line
End Using
End Function
This is because lines of text are variable-length records, and there is no way to guess the exact file offset where a specific line begins — not without an index.
If you frequently need to load a specific line, you have some more options:
Load the complete text file into memory, e.g. by using File.ReadAllLines("Foobar.txt"). This returns a String() array which you can access by line number directly.
Create a line number index manually. That is, process a text file line by line, and fill a Dictionary(Of Integer, Integer) as you go. The keys are line numbers, and the values are file offsets. This allows you to .Seek right to the beginning of a specific line without having to keep the whole file in memory.
Try this:
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim reader As New System.IO.StreamReader("C:\text.txt")
Dim allLines As List(Of String) = New List(Of String)
Do While Not reader.EndOfStream
allLines.Add(reader.ReadLine())
Loop
reader.Close()
txtFirstName.Text = ReadLine(5, allLines)
txtLastName.Text = ReadLine(6, allLines)
End Sub
Public Function ReadLine(lineNumber As Integer, lines As List(Of String)) As String
Return lines(lineNumber - 1)
End Function
If you had a file with this:
Line 1
Line 2
Line 3
Line 4
My Name
My LastName
your name textbox will have 'My Name' and your LastName textbox will have 'My LastName'.
This is very simple, try this:
Dim strLineText As String
Dim intLineNumber As Integer
LineNumber=3
myLine = File.ReadAllLines("D:\text.txt").ElementAt(LineNumber).ToString
Yet another option
Private Function readNthLine(fileAndPath As String, lineNumber As Integer) As String
Dim nthLine As String = Nothing
Dim n As Integer
Try
Using sr As StreamReader = New StreamReader(fileAndPath)
n = 0
Do While (sr.Peek() >= 0) And (n < lineNumber)
sr.ReadLine()
n += 1
Loop
If sr.Peek() >= 0 Then
nthLine = sr.ReadLine()
End If
End Using
Catch ex As Exception
Throw
End Try
Return nthLine
End Function
i tried this and it works fine. using VB Express
content inside test.txt:
line1
line2
1
John
then in the form i add
textbox1
textbox2
label1
label2
and a button.
code inside the button:
Private Sub Button2_Click_1(sender As Object, e As EventArgs) Handles Button2.Click
Dim myLine As String
Dim lineNumber0 As Integer
lineNumber0 = 0
Dim lineNumber1 As Integer
lineNumber1 = 1
Dim lineNumber2 As Integer
lineNumber2 = 2
Dim lineNumber3 As Integer
lineNumber3 = 3
TextBox1.Text=File.ReadAllLines("D:\test.txt").ElementAt(lineNumber0).ToString
TextBox2.Text=File.ReadAllLines("D:\test.txt").ElementAt(lineNumber1).ToString
Label1.Text = File.ReadAllLines("D:\test.txt").ElementAt(lineNumber2).ToString
Label2.Text = File.ReadAllLines("D:\test.txt").ElementAt(lineNumber3).ToString
End Sub
Here's a simple but effective solution:
Dim Reader As String = System.IO.File.ReadAllLines("C:\File.txt")(1)
MsgBox("Line 1: " + Reader)
The MsgBox should show the first line of C:\File.txt.

Read Text File and Output Multiple Lines to a Textbox

I'm trying to read a text file with multiple lines and then display it in a textbox. The problem is that my program only reads one line. Can someone point out the mistake to me?
Imports System.IO
Imports Microsoft.VisualBasic.FileIO
Public Class Form1
Private BagelStreamReader As StreamReader
Private PhoneStreamWriter As StreamWriter
Dim ResponseDialogResult As DialogResult
Private Sub OpenToolStripMenuItem_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles OpenToolStripMenuItem.Click
'Dim PhoneStreamWriter As New StreamWriter(OpenFileDialog1.FileName)
'Is file already open
If PhoneStreamWriter IsNot Nothing Then
PhoneStreamWriter.Close()
End If
With OpenFileDialog1
.InitialDirectory = Directory.GetCurrentDirectory
.FileName = OpenFileDialog1.FileName
.Title = "Select File"
ResponseDialogResult = .ShowDialog()
End With
'If ResponseDialogResult <> DialogResult.Cancel Then
' PhoneStreamWriter = New StreamWriter(OpenFileDialog1.FileName)
'End If
Try
BagelStreamReader = New StreamReader(OpenFileDialog1.FileName)
DisplayRecord()
Catch ex As Exception
MessageBox.Show("File not found or is invalid.", "Data Error")
End Try
End Sub
Private Sub DisplayRecord()
Do Until BagelStreamReader.Peek = -1
TextBox1.Text = BagelStreamReader.ReadLine()
Loop
'MessageBox.Show("No more records to display.", "End of File")
'End If
End Sub
Private Sub SaveToolStripMenuItem_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles SaveToolStripMenuItem.Click
With SaveFileDialog1
.InitialDirectory = Directory.GetCurrentDirectory
.FileName = OpenFileDialog1.FileName
.Title = "Select File"
ResponseDialogResult = .ShowDialog()
End With
PhoneStreamWriter.WriteLine(TextBox1.Text)
With TextBox1
.Clear()
.Focus()
End With
TextBox1.Clear()
End Sub
Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
Dim PhoneStreamWriter As New StreamWriter(OpenFileDialog1.FileName)
PhoneStreamWriter.Close()
Me.Close()
End Sub
End Class
Here is a sample textfile:
Banana nut
Blueberry
Cinnamon
Egg
Plain
Poppy Seed
Pumpkin
Rye
Salt
Sesame seed
You're probably only getting the last line in the file, right? Your code sets TextBox1.Text equal to BagelSteramReader.ReadLine() every time, overwriting the previous value of TextBox1.Text. Try TextBox1.Text += BagelStreamReader.ReadLine() + '\n'
Edit: Though I must steal agree with Hans Passant's commented idea on this; If you want an more efficient algorithm, File.ReadAllLines() even saves you time and money...though I didn't know of it myself. Darn .NET, having so many features...
I wrote a program to both write to and read from a text file. To write the lines of a list box to a text file I used the following code:
Private Sub txtWriteToTextfile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtWriteToTextfile.Click
Dim FileWriter As StreamWriter
FileWriter = New StreamWriter(FileName, False)
' 3. Write some sample data to the file.
For i = 1 To lstNamesList.Items.Count
FileWriter.Write(lstNamesList.Items(i - 1).ToString)
FileWriter.Write(Chr(32))
Next i
FileWriter.Close()
End Sub
And to read and write the contents of the text file and write to a multi-line text box (you just need to set the multiple lines property of a text box to true) I used the following code. I also had to do some extra coding to break the individual words from the long string I received from the text file.
Private Sub cmdReadFromTextfile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdReadFromTextfile.Click
Dim sStringFromFile As String = ""
Dim sTextString As String = ""
Dim iWordStartingPossition As Integer = 0
Dim iWordEndingPossition As Integer = 0
Dim iClearedTestLength As Integer = 0
Dim FileReader As StreamReader
FileReader = New StreamReader(FileName)
sStringFromFile = FileReader.ReadToEnd()
sTextString = sStringFromFile
txtTextFromFile.Text = ""
Do Until iClearedTestLength = Len(sTextString)
iWordEndingPossition = CInt(InStr((Microsoft.VisualBasic.Right(sTextString, Len(sTextString) - iWordStartingPossition)), " "))
txtTextFromFile.Text = txtTextFromFile.Text & (Microsoft.VisualBasic.Mid(sTextString, iWordStartingPossition + 1, iWordEndingPossition)) & vbCrLf
iWordStartingPossition = iWordStartingPossition + iWordEndingPossition
iClearedTestLength = iClearedTestLength + iWordEndingPossition
Loop
FileReader.Close()
End Sub