Read Text File and Output Multiple Lines to a Textbox - vb.net

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

Related

Reading and writing files causes "The process cannot access the file because it is being used by another process" error

I'm very new to coding so my code is very basic but I am trying to rewrite a file using an item selected from a list box. The code is a recreation of my full code so it's not as thorough but I want to be able to change the "availability" of a product for a website (In theory because this is not a professional project). When I try to read or write the file an error message comes up saying "The process cannot access the file because it is being used by another process".
Dim FileRewrite As String = "FileRewrite.txt"
Dim ValidateID As Boolean
Dim Read As String
Dim IDR As String
Dim YNR As String
Private Sub TxtBxID_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TxtBxID.TextChanged
If TxtBxID.Text.Length = 2 Then
ValidateID = True
Else
ValidateID = False
End If
End Sub
Private Sub BtnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnAdd.Click
Dim ID As String
Dim YN As String
Dim Writer As New System.IO.StreamWriter(FileRewrite, True)
If ValidateID = True Then
ID = TxtBxID.Text
If CBxYN.Checked = True Then
YN = "YES"
Else
YN = "NO "
End If
Writer.WriteLine(LSet(ID, 3) & LSet(YN, 3))
Writer.Close()
LstBxItems.Items.Clear()
Dim Reader As New System.IO.StreamReader(FileRewrite, True)
Do While Reader.Peek >= 0
LstBxItems.Items.Add(Reader.ReadLine)
Loop
Reader.Close()
Else
MsgBox("Please enter a 2 digit ID")
End If
End Sub
Private Sub BtnChange_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnChange.Click
Dim ItemToChange As String
Dim Reader As New System.IO.StreamReader(FileRewrite, True)
ItemToChange = LstBxItems.SelectedItem
IDR = Mid(ItemToChange, 1, 3)
YNR = Mid(ItemToChange, 4, 6)
Do While Reader.Peek >= 0
Read = Reader.ReadLine
Writer()
Loop
Reader.Close()
End Sub
Private Sub Writer()
Dim Writer As New System.IO.StreamWriter(FileRewrite, True)
If Mid(Read, 1, 3) = IDR Then
If YNR = "YES" Then
YNR = "NO "
Else
YNR = "YES"
End If
Writer.WriteLine(LSet(IDR, 3) & LSet(YNR, 3))
Writer.Close()
End If
End Sub
I expect the availability of the product in the file to change from yes to no or no to yes but the reader and writer will not work
You cannot write to the file while looping through the same file to read via Reader.Peek

ProgressBar not updating using a For Each loop

I'm copying all the .avi and .png files from one folder into another:
Private Sub CopierSend_Button_Click(sender As Object, e As EventArgs) Handles CopierSend_Button.Click
If MessageBox.Show("Click OK to send media or just Cancel.", "Media Copier", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) = DialogResult.OK Then
For Each foundFile As String In My.Computer.FileSystem.GetFiles(FrapsFolder_, Microsoft.VisualBasic.FileIO.SearchOption.SearchTopLevelOnly, "*.avi", "*.png")
Dim foundFileInfo As New System.IO.FileInfo(foundFile)
My.Computer.FileSystem.CopyFile(foundFile, DestFolder_ & foundFileInfo.Name, Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs, Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing)
Next
Else
'Nothing Yet
End If
End Sub
I want to add a ProgressBar which will count every time a file is copied, so I added this code before the For Each loop:
Dim file1() As String = IO.Directory.GetFiles(FrapsFolder_, "*.avi")
Dim file2() As String = IO.Directory.GetFiles(FrapsFolder_, "*.png")
Dim files = file1.Length + file2.Length
Copier_ProgressBar.Step = 1
Copier_ProgressBar.Maximum = files
And added this code inside the For Each loop:
Copier_ProgressBar.Value += 1
Here is all of my code:
Private Sub CopierSend_Button_Click(sender As Object, e As EventArgs) Handles CopierSend_Button.Click
If MessageBox.Show("Click OK to send media or just Cancel.", "Media Copier", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) = DialogResult.OK Then
Dim file1() As String = IO.Directory.GetFiles(FrapsFolder_, "*.avi")
Dim file2() As String = IO.Directory.GetFiles(FrapsFolder_, "*.png")
Dim files = file1.Length + file2.Length
Copier_ProgressBar.Step = 1
Copier_ProgressBar.Maximum = files
For Each foundFile As String In My.Computer.FileSystem.GetFiles(FrapsFolder_, Microsoft.VisualBasic.FileIO.SearchOption.SearchTopLevelOnly, "*.avi", "*.png")
Dim foundFileInfo As New System.IO.FileInfo(foundFile)
My.Computer.FileSystem.CopyFile(foundFile, DestFolder_ & foundFileInfo.Name, Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs, Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing)
Copier_ProgressBar.Value += 1
Next
Else
'Nothing Yet
End If
End Sub
The ProgressBar updates, but only after all the files have been copied instead of updating in real time. Any idea?
As it stands it looks like the ProgressBar doesn't do anything until after all the files have copied. That isn't strictly true. Instead your UI is not updating.
Instead you should look into using a BackgroundWoker to report progress. Something like this should do the trick:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'This can also be set using the Designer
BackgroundWorker1.WorkerReportsProgress = True
End Sub
Private Sub CopierSend_Button_Click(sender As Object, e As EventArgs) Handles CopierSend_Button.Click
If MessageBox.Show("Click OK to send media or just Cancel.", "Media Copier", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) = DialogResult.OK Then
Dim file1() As String = IO.Directory.GetFiles(FrapsFolder_, "*.avi")
Dim file2() As String = IO.Directory.GetFiles(FrapsFolder_, "*.png")
Dim files As Integer = file1.Length + file2.Length
Copier_ProgressBar.Step = 1
Copier_ProgressBar.Maximum = files
BackgroundWorker1.RunWorkerAsync()
End If
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
For Each foundFile As String In My.Computer.FileSystem.GetFiles(FrapsFolder_, Microsoft.VisualBasic.FileIO.SearchOption.SearchTopLevelOnly, "*.avi", "*.png")
Dim foundFileInfo As New System.IO.FileInfo(foundFile)
My.Computer.FileSystem.CopyFile(foundFile, DestFolder_ & foundFileInfo.Name, Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs, Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing)
BackgroundWorker1.ReportProgress(Copier_ProgressBar.Value + 1)
Next
End Sub
Private Sub BackgroundWorker1_ProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
Copier_ProgressBar.Value = e.ProgressPercentage
End Sub
As an additional note, for best practice, I would consider using Path.Combine instead of concatenating strings together:
My.Computer.FileSystem.CopyFile(foundFile, Path.Combine(DestFolder_, foundFileInfo.Name), Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs, Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing)

Reading a text file into an array does nothing when Submit is clicked

I need this program to take the countries.txt file and read it into the country.countryarray when the program loads. Then the user needs to be able to enter a country name in the nmtext.text field and click submit and the country abbreviation should be pulled from the array and displayed in the abbrevtext.text field and complete the same action if the user searches an abbreviation from the abbrevtext.text field then it needs to display the country name in the nmtext.text field.
The countries.txt file has 250 countries and has to be stored in the debug file for the project and the contents of the file look like this when viewed in notepad++ with a carriage return at the end of each line.
0.AC
1.Ascension Island
2.AD
3.Andorra
4.AE
5.United Arab Emirates
6.AF
7.Afghanistan
8.AG
9.Antigua and Barbuda
10.AI
Here is my code so far and it is not working it will pop up the form and let me enter a country name but it doesn't do anything when I hit submit.
Imports System.IO
Imports Microsoft.VisualBasic.FileIO
Public Class CountForm
'CREATES STRUCTURE AND ARRAY
Public Structure Countries
Public CountryArray
Public CountryString As String
End Structure
'CREATES OBJECT FOR STRUCTURE
Public Country As Countries
'CREATES STREAM READER
Private MyStreamReader As System.IO.StreamReader
'CREATES FILESTRING VARIALE TO REFERENCE THE FILE PATH
Public FileString As String = "C:\Users\User\Desktop\Basic\CountryFile\CountryFile\bin\Debug\Countries.Txt"
'CREATES TEXTFIELDPARSER AND REFERENCES FILESTRING TO CALL THE FILEPATH
Private TextFieldParser As New TextFieldParser(FileString)
Private Sub CountForm_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Try
Country.CountryArray = File.ReadAllText(FileString) '// gets all the text in the file'
Catch ex As Exception
Dim ResponseDialogResult As String
' File missing.
ResponseDialogResult = MessageBox.Show("Something Went Wrong",
"Debuging Purposes", MessageBoxButtons.OK,
MessageBoxIcon.Question)
If ResponseDialogResult = DialogResult.Yes Then
End If
If ResponseDialogResult = DialogResult.No Then
' Exit the program.
Me.Close()
End If
End Try
End Sub
Private Sub Submit_Click(sender As System.Object, e As System.EventArgs) Handles Submit.Click
Try
TextFieldParser.TextFieldType = FieldType.Delimited
TextFieldParser.SetDelimiters(Environment.NewLine)
Do Until MyStreamReader.Peek = -1
If NmText.Text.ToUpper.Contains(Country.CountryArray.ToUpper()) Then
AbbrevText.Text = Country.CountryArray.ToUpper - 1
Else
MessageBox.Show("Name or Abbreviation Was Not Found", "Error", MessageBoxButtons.OK)
End If
Loop
Catch ex As Exception
End Try
End Sub
Private Sub Clear_Click(sender As System.Object, e As System.EventArgs) Handles Clear.Click
NmText.Text = ""
AbbrevText.Text = ""
End Sub
End Class
The StreamReader/TextFieldParser approach seems really complicated. Maybe this works for you:
Public Class Form1
Private countryDict As New Dictionary(Of String, String)
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim lineArray = IO.File.ReadAllLines("countries.txt")
'this will cause trouble if there is a NewLine at the end of the file
'In this case just remove the last new line.
For index = 0 To lineArray.Length - 2 Step 2
countryDict.Add(lineArray(index), lineArray(index + 1))
Next
End Sub
Private Sub Submit_Click(sender As System.Object, e As System.EventArgs) Handles Submit.Click
If countryDict.ContainsKey(NmText.Text.ToUpper()) Then
AbbrevText.Text = countryDict(NmText.Text.ToUpper())
Else
MsgBox("Name or Abbreviation Was Not Found")
End If
End Sub
End Class

Save Data to text tile using SaveFileDialog?

I have already viewed the MSDN Example but I am still having problems.
I created a super-simple program to multiply two numbers, and display the output in the textbox. Now I need to be able to read that text box value and put the value in a text file, bringing up the save to file dialog when the "Save To File" button is clicked.
Private Sub MutiplyBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MutiplyBtn.Click
Dim FirstNum As Double = Num1.Text
Dim SecondNum As Double = Num2.Text
Dim Answer2 As Double = FirstNum * SecondNum
Answerbox.Text = Answer2
End Sub
Private Sub SaveResultToFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveResultToFile.Click
Dim myStream As Stream
Dim saveFileDialog1 As New SaveFileDialog()
saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
saveFileDialog1.FilterIndex = 2
saveFileDialog1.RestoreDirectory = True
If saveFileDialog1.ShowDialog() = DialogResult.OK Then
myStream = saveFileDialog1.OpenFile()
If (myStream IsNot Nothing) Then
System.IO.File.WriteAllText(Answerbox.Text)
myStream.Close()
End If
End If
End Sub
Currently, Visual Studio is giving me an error: Overload resolution failed because no accessible 'WriteAllText' accepts this number of arguments.
WriteAllText static method requires the name of the file where the data should be written to.
You could use directly the name selected in the saveFileDialog1
If saveFileDialog1.ShowDialog() = DialogResult.OK Then
System.IO.File.WriteAllText(saveFiledialog1.FileName, Answerbox.Text)
End If
instead if you really want to use the stream opened by OpenFile() method your code should be
If saveFileDialog1.ShowDialog() = DialogResult.OK Then
Dim sw As StreamWriter = new StreamWriter(saveFileDialog1.OpenFile())
If (sw IsNot Nothing) Then
sw.WriteLine(Answerbox.Text)
sw.Close()
End If
End If
The code is an example, you need to add a bit of error handling
Hi I tried above method but I succeed in this way....
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
SaveFileDialog1.Filter = "TXT Files (*.txt*)|*.txt"
If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK _
Then
My.Computer.FileSystem.WriteAllText _
(SaveFileDialog1.FileName, RichTextBox1.Text, True)
End If
End Sub

Iteration of a text file in Visual Basic

Ok, so I'm making a program that will read from a text file, convert each line into an array, the. Send each of those lines 1 per tick. This is in 2010 Visual Basic.
Closest I've gotten is sending all at once, I worked on it over night and am slowly destroying it.
Ideally, I want Button 1 click to populate the array from the file at LocationTB then start the timer. The timer should send a line at a time on the GapTB interval.
Public Class Form1
Public TextLine As String
Public MyFileName As String
Public MyNewLine(1000) As String
Private Property z As Integer
Private Property objReader As Object
Public Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If RadioButton2.Checked = True Then
Dim Textline As String = ""
Dim FILE_NAME As String = LocationTB.Text
Dim objReader As New System.IO.StreamReader(FILE_NAME)
MyFileName = LocationTB.Text
FileOpen(1, MyFileName, OpenMode.Input, OpenAccess.Read, OpenShare.Shared)
z = 0
Do Until EOF(1)
MyNewLine(z) = LineInput(1)
z = z + 1
Loop
FileClose(1)
End If
Timer1.Interval = GapTB.Text
Timer1.Enabled = True
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
If RadioButton1.Checked = True Then
AppActivate(Hook.Text)
SendKeys.Send(SimpleTB.Text)
SendKeys.Send((Chr(13)))
ElseIf RadioButton2.Checked = True Then
For Each
TextLine = TextLine & objReader.ReadLine
AppActivate(Hook.Text)
SendKeys.Send(TextLine)
SendKeys.Send((Chr(13)))
Next
Else
MsgBox("File Does Not Exist")
End If
End Sub
Is this the kind of thing you're looking for?
It'll write the contents of a file (in this instance "C:\mark.txt") to the output window in Visual Studio.
Public Class Form1
Private myTimer As Timer
Private lines As String()
Private currentLine As Integer
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
lines = IO.File.ReadAllLines("C:\mark.txt")
currentLine = 0
myTimer = New Timer()
AddHandler myTimer.Tick, AddressOf myTimer_Tick
myTimer.Interval = 1000
myTimer.Enabled = True
End Sub
Private Sub myTimer_Tick(sender As Object, e As EventArgs)
If currentLine < lines.Count Then
Dim lineToSend As String = lines(currentLine)
Debug.Print(lineToSend)
currentLine += 1
Else
myTimer.Enabled = False
End If
End Sub
End Class
Caveat
The above code isn't scalable. If you're SURE the file will always be small then it will do (that said, they're never always small).
To make this scalable you'd need to hold the file open, and read each line as you need it, not load the entire file contents at once.
I know how to do it to a application I started myself: Here's the code to make Calculator work:
Dim ProcID As Integer
' Start the Calculator application, and store the process id.
ProcID = Shell("CALC.EXE", AppWinStyle.NormalFocus)
' Activate the Calculator application.
AppActivate(ProcID)
' Send the keystrokes to the Calculator application.
My.Computer.Keyboard.SendKeys("22", True)
My.Computer.Keyboard.SendKeys("*", True)
My.Computer.Keyboard.SendKeys("44", True)
My.Computer.Keyboard.SendKeys("=", True)
' The result is 22 * 44 = 968.
AppActivate should know the exact title of the form to activate. If not known, iterate the Processes to locate yours. If the title is correctly specified it should work