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

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

Related

Download a file from google drive

First of all, sorry for my english. Second, I want to make an app that, at every launch download a .txt file from google drive, the file is defined (I mean, it's in drive). It's just a single file, but, when I launch the app, the file is downloaded, but dosen't contain anything..
Here is my code:
Private Function ReadLine(ByVal Line As Integer, ByVal lista As List(Of String)) As String
Return lista(Line - 1)
End Function
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If My.Computer.Network.IsAvailable() = True Then
Try
My.Computer.FileSystem.DeleteFile("C:\WINDOWS\" & fisier)
Catch ex As Exception
End Try
My.Computer.Network.DownloadFile("https://doc-14-7c-docs.googleusercontent.com/docs/securesc/17t22h2a63tpkhdgv047v6i0s5a9o8bm/qgqjocmi87jt0up72gfpg9dseeo3pt84/1458396000000/07699472972018131827/07699472972018131827/0B8iVIf__yN1FUDV1STNWODJUYms?e=download&nonce=5jnki0mtgo520&user=07699472972018131827&hash=0gi5r6k7rm2uob14062tlbsk0nhpkoo1", _
"C:\WINDOWS\" & fisier)
Dim reader As New IO.StreamReader("C:\WINDOWS\" & fisier)
Dim lista As New List(Of String)
While Not reader.EndOfStream
lista.Add(reader.ReadLine)
End While
reader.Close()
If My.Computer.FileSystem.FileExists(fisier2) = False Then
lblWould.Text = ReadLine(1, lista)
Else
Dim nr As Integer
nr = Val(My.Computer.FileSystem.ReadAllText(fisier2))
nrx = nr
End If
Dim contain As String = My.Computer.FileSystem.ReadAllText("C:\WINDOWS\" & fisier)
contain = contain.Replace(lblWould.Text, "SEEN!")
My.Computer.FileSystem.WriteAllText("C:\WINDOWS\" & fisier, contain, False)
Else
MsgBox("Trebuie sa fi connectat la internet!")
Me.Close()
End If
End Sub
Private Sub btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnYes.Click, btnNo.Click
Dim reader As New IO.StreamReader("C:\WINDOWS\" & fisier)
Dim lista As New List(Of String)
Dim a As String
While Not reader.EndOfStream
a = reader.ReadLine()
If Not a = "SEEN!" Then
lista.Add(reader.ReadLine)
End If
End While
lblWould.Text = lista(nrx + 1)
nrx += 1
Dim contain As String = My.Computer.FileSystem.ReadAllText("C:\WINDOWS\" & fisier)
contain = contain.Replace(lblWould.Text, "SEEN!")
My.Computer.FileSystem.WriteAllText("C:\WINDOWS\" & fisier, contain, False)
End Sub`
Thanks!

VB.NET Read .Txt File Into Multiple Text Boxes

I have a program that I can enter in names and integer values in the text boxes and then save those to a file. That works perfectly fine but the part I need help with is the reading of the file.
The data is saved into the file much like a csv file. example:
Test, 5, 5, 5
dadea, 5, 5, 5
das, 5, 5, 5
asd, 5, 5, 5
dsadasd, 5, 5, 5
My problem is, how do I read that into multiple text boxes on my form?
The names (first value of each row) should go into their corresponding Name textbox (i.e. txtName0, txtName1, txtName2, etc.) and the integer values should also go into their corresponding text boxes (txtCut1, txtColour1, etc.).
I have spent the past 2 hours trying to figure this out but I just cant.
The part I need help with is the last method.
Imports System.IO
Public Class Form1
Private aPricesGrid(,) As TextBox
Private aAverages() As TextBox
Private aNames() As TextBox
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
aPricesGrid = {{txtCut1, txtColour1, txtUpDo1, txtHighlight1, txtExtensions1},
{txtCut2, txtColour2, txtUpDo2, txtHighlight2, txtExtensions2},
{txtCut3, txtColour3, txtUpDo3, txtHighlight3, txtExtensions3},
{txtCut4, txtColour4, txtUpDo4, txtBHighlight4, txtExtensions4},
{txtCut5, txtColour5, txtUpDo5, txtHighlight5, txtExtensions5}}
aAverages = {txtAvg0, txtAvg1, txtAvg2, txtAvg3, txtAvg4}
aNames = {txtName0, txtName1, txtName2, txtName3, txtName4}
End Sub
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
For nCol As Integer = 0 To 4
Dim nColTotal As Integer = 0
Dim nColItems As Integer = 0
For nRow As Integer = 0 To 2
Try
nColTotal += aPricesGrid(nRow, nCol).Text
nColItems += 1
Catch ex As Exception
End Try
Next
aAverages(nCol).Text = (nColTotal / nColItems).ToString("c")
Next
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
For Each txt As Control In Me.Controls
If TypeOf txt Is TextBox Then
txt.Text = String.Empty
End If
Next
End Sub
Private Sub SaveToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SaveToolStripMenuItem.Click
Dim oSaveFileDialog As New SaveFileDialog()
'Display the Common file Dialopg to user
oSaveFileDialog.Filter = "Text Files (*.txt)|*.txt"
If oSaveFileDialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
' Retrieve Name and open it
Dim fileName As String = oSaveFileDialog.FileName
Dim outputFile As StreamWriter = File.CreateText(fileName)
For nRow As Integer = 0 To 4
outputFile.Write(aNames(nRow).Text)
For nCol As Integer = 0 To 2
outputFile.Write(", " & aPricesGrid(nRow, nCol).Text)
Next
outputFile.WriteLine()
Next
outputFile.Close()
End If
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub
Private Sub ReadToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ReadToolStripMenuItem.Click
Dim oOpenFileDialog As New OpenFileDialog()
'Display the Common file Dialopg to user
oOpenFileDialog.Filter = "Text Files (*.txt)|*.txt"
If oOpenFileDialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
Dim fileName As String = oOpenFileDialog.FileName
Dim OpenFile As StreamReader = File.OpenText(fileName)
End If
End Sub
End Class
Try this method.
Dim mindex as integer
Dim string1 as string()
Dim OpenFile As StreamReader = File.OpenText(fileName)
While OpenFile .Peek <> -1
string1= OpenFile .ReadLine.Split(",")
If mindex = 0 Then
txtname1.text=string1(0)
txtcut1.text=string1(1)
txtcolour1.text=string1(2)
'add other textboxes
ElseIf mindex = 1 Then
txtname2.text=string1(0)
txtcut2.text=string1(1)
txtcolour2.text=string1(2)
'add other textboxes
ElseIf mindex = 2 Then
txtname3.text=string1(0)
txtcut3.text=string1(1)
txtcolour3.text=string1(2)
'add other textboxes
ElseIf mindex = 3 Then
'your code
ElseIf mindex = 4 Then
'your code
End If
mindex += 1
End While
OpenFile .Close()
hope this helps.

Download File With Start / Pause / Stop

Is there any way i can pause a file download in my vb program?? I have tried both the http method and the my.computer.net method with no luck. I have also tried pausing the background worker by this method: [URL] But even if the bgworker is paused the download goes on.....
Dim locationfiledownload As String
Dim whereToSave As String 'Where the program save the file
Delegate Sub ChangeTextsSafe(ByVal length As Long, ByVal position As Integer, ByVal percent As Integer, ByVal speed As Double)
Delegate Sub DownloadCompleteSafe(ByVal cancelled As Boolean)
Public Sub DownloadComplete(ByVal cancelled As Boolean)
ToolStripButton2.Enabled = True
ToolStripButton3.Enabled = False
If cancelled Then
Me.Label4.Text = "Cancelled"
MessageBox.Show("Download aborted", "Aborted", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
Me.Label4.Text = "Successfully downloaded"
MessageBox.Show("Successfully downloaded!", "All OK", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
Me.RadProgressBar1.Value1 = 0
Me.Label4.Text = ""
End Sub
Public Sub ChangeTexts(ByVal length As Long, ByVal position As Integer, ByVal percent As Integer, ByVal speed As Double)
Me.Label4.Text = "Downloaded " & Math.Round((position / 1024), 2) & " KB of " & Math.Round((length / 1024), 2) & "KB"
Me.RadProgressBar1.Value1 = percent
End Sub
Public Sub btnDownload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton2.Click
locationfiledownload = GetPage("http://asankonkur.ir/update/locationfiledownload.txt")
If locationfiledownload <> "" AndAlso locationfiledownload.StartsWith("http://") Then
Me.SaveFileDialog1.FileName = locationfiledownload.Split("/"c)(locationfiledownload.Split("/"c).Length - 1)
If Me.SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
Me.whereToSave = Me.SaveFileDialog1.FileName
Me.SaveFileDialog1.FileName = ""
ToolStripButton2.Enabled = False
ToolStripButton3.Enabled = True
Me.BackgroundWorker2.RunWorkerAsync() 'Start download
End If
Else
MessageBox.Show("Please insert valid URL for download", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning)
End If
End Sub
Private Sub BackgroundWorker2_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker2.DoWork
'Creating the request and getting the response
Dim theResponse As HttpWebResponse
Dim theRequest As HttpWebRequest
Try 'Checks if the file exist
theRequest = WebRequest.Create(locationfiledownload)
theResponse = theRequest.GetResponse
Catch ex As Exception
MessageBox.Show("An error occurred while downloading file. Possibe causes:" & ControlChars.CrLf & _
"1) File doesn't exist" & ControlChars.CrLf & _
"2) Remote server error", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Dim cancelDelegate As New DownloadCompleteSafe(AddressOf DownloadComplete)
Me.Invoke(cancelDelegate, True)
Exit Sub
End Try
Dim length As Long = theResponse.ContentLength 'Size of the response (in bytes)
Dim safedelegate As New ChangeTextsSafe(AddressOf ChangeTexts)
Me.Invoke(safedelegate, length, 0, 0, 0) 'Invoke the TreadsafeDelegate
Dim writeStream As New IO.FileStream(Me.whereToSave, IO.FileMode.Create)
'Replacement for Stream.Position (webResponse stream doesn't support seek)
Dim nRead As Integer
'To calculate the download speed
Dim speedtimer As New Stopwatch
Dim currentspeed As Double = -1
Dim readings As Integer = 0
Do
If BackgroundWorker2.CancellationPending Then 'If user abort download
Exit Do
End If
speedtimer.Start()
Dim readBytes(4095) As Byte
Dim bytesread As Integer = theResponse.GetResponseStream.Read(readBytes, 0, 4096)
nRead += bytesread
Dim percent As Short = (nRead * 100) / length
Me.Invoke(safedelegate, length, nRead, percent, currentspeed)
If bytesread = 0 Then Exit Do
writeStream.Write(readBytes, 0, bytesread)
speedtimer.Stop()
readings += 1
If readings >= 5 Then 'For increase precision, the speed it's calculated only every five cicles
currentspeed = 20480 / (speedtimer.ElapsedMilliseconds / 1000)
speedtimer.Reset()
readings = 0
End If
Loop
'Close the streams
theResponse.GetResponseStream.Close()
writeStream.Close()
If Me.BackgroundWorker2.CancellationPending Then
IO.File.Delete(Me.whereToSave)
Dim cancelDelegate As New DownloadCompleteSafe(AddressOf DownloadComplete)
Me.Invoke(cancelDelegate, True)
Exit Sub
End If
Dim completeDelegate As New DownloadCompleteSafe(AddressOf DownloadComplete)
Me.Invoke(completeDelegate, False)
End Sub
Private Sub mainForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.Label4.Text = ""
End Sub
Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton3.Click
Me.BackgroundWorker2.CancelAsync() 'Send cancel request
End Sub
In your code, you are using WebRequest.Create(locationfiledownload). By default, this creates a request header that asks for the entire file. You need to edit the request and add a Range header that asks for the specific byte range of the file you're looking for. E.g., adding to the WebRequest.Headers.Range.Ranges collection. Unfortunately, this is going to make your code quite a bit more complex as you will need to store details of what's already been download somewhere (assuming you want to resume after application close/restart). You'll need to know;
How much of the file (if any) is already downloaded
How much you intend downloading at any one time
Once you know this, you will have to form a request with a Range header for X bytes of the file. Once you receive it, you'll need to save it and ask for the next section. An example written in C# is available on The Code Project here: http://www.codeproject.com/Tips/307548/Resume-Suppoert-Downloading

sequential access file in vb

I am working on a program in Visual Basic that incorporates using a sequential access file for a ballot type program. Each type the user clicks the save vote button, the amount of votes gets stored. What I am trying to do is in my access file is to display the number of votes as an actual number. The way my program is written right now, the name of the candidate appears as many times as the vote was saved. for example, if perez was voted for 4 times, in the access file perez is displayed on 4 different lines. How do I display the actual number of how many time they were voted for. I'm thinking using a counter variable, but not really sure how to really implement it in. this is what i have so far.
Public Class Voter
Dim file As IO.File
Dim infile As IO.StreamReader
Dim outfile As IO.StreamWriter
Private Sub Voter_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
outfile = IO.File.CreateText("Votes.txt")
End Sub
Private Sub btnVote_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnVote.Click
lstResult.Items.Clear()
'which buttons is clicked
If radMark.Checked = True Then
outfile.WriteLine(radMark.Text)
radMark.Checked = False
ElseIf radSheima.Checked = True Then
outfile.WriteLine(radSheima.Text)
radSheima.Checked = False
ElseIf radSam.Checked = True Then
outfile.WriteLine(radSam.Text)
radSam.Checked = False
Else
MessageBox.Show("You should select one among them")
End If
End Sub
Private Sub btnResult_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnResult.Click
'Dim Mark, Sheima, Sam As Integer
Dim Mark As Integer = 0
Dim Sheima As Integer = 0
Dim Sam As Integer = 0
Dim name As String
'Mark = Sheima = Sam = 0
outfile.Close()
infile = IO.File.OpenText("Votes.txt")
'keep track of votes
While Not infile.EndOfStream
name = infile.ReadLine()
If name.Equals("Mark Stone") Then
Mark += 1
ElseIf name.Equals("Sheima Patel") Then
Sheima += 1
Else
Sam += 1
End If
End While
'results
lstResult.Items.Clear()
lstResult.Items.Add("Mark Stone " & CStr(Mark))
lstResult.Items.Add("Shemia Patel " & CStr(Sheima))
lstResult.Items.Add("Sam Perez " & CStr(Sam))
infile.Close()
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Me.Close()
End Sub
End Class
In your btnVote_Click function you are writing the radiobutton text into the file everytime you click on it, that's how the issue to be created.
Also you are counting how many times the name appears in the file as the number of vote but not the number.
You should try putting the name and count in your vote file rather than just the name, e.g.
Mark,1
Sheima,2
Same,5
Then when you click Vote button, you should read the number for Mark, increment by 1 and write it back.
Try this,
Private Sub btnVote_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnVote.Click
lstResult.Items.Clear()
'which buttons is clicked
If radMark.Checked = True Then
AddCount(radMark.Text)
radMark.Checked = False
ElseIf radSheima.Checked = True Then
AddCount(radSheima.Text)
radSheima.Checked = False
ElseIf radSam.Checked = True Then
AddCount(radSam.Text)
radSam.Checked = False
Else
MessageBox.Show("You should select one among them")
End If
End Sub
Private Sub btnResult_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnResult.Click
'results
lstResult.Items.Clear()
lstResult.Items.Add("Mark Stone " & GetCount(radMark.Text))
lstResult.Items.Add("Shemia Patel " & CStr(radSheima.Text))
lstResult.Items.Add("Sam Perez " & CStr(radSam.Text))
End Sub
Private Sub AddCount(Byval VoteName As String)
infile = New IO.File.StreamReader("Votes.txt")
Dim whole_line As String
Dim person As String
Dim vote_count As Integer
Dim found as boolean
'read through the whole file until the end or find the name
Do While infile.Peek() >= 0 And person <> VoteName
'read each line
whole_line = infile.ReadLine
person = Split(whole_line, ",")(0)
If person = VoteName Then
vote_count = Split(whole_line, ",")(1)
found = True
End If
Loop
'Close the file after it is used.
infile.Close()
'Reopen the file with the StreamWriter
outfile = IO.File.OpenText("Votes.txt")
If found = True Then
'the line will only be replace if the person name is found in the line
whole_line = Whole_line.replace(VoteName & "," & vote_count, VoteName & "," & vote_count + 1)
'Write back into the file
outfile.WriteLine(whole_line)
Else
'if the vote name is not found in the file
'Then create a new one
outfile.WriteLine(VoteName & ",1" & VbCrLf)
End If
outfile.Close()
End Sub
Private Function GetCount(Byval VoteName As String)
infile = New IO.File.StreamReader("Votes.txt")
Dim whole_line As String
Dim person As String
Dim vote_count As Integer
'read through the whole file
Do While infile.Peek() >= 0 And person <> VoteName
'read each line
whole_line = infile.ReadLine
person = Split(Whole_line, ",")(0)
If person = VoteName Then
vote_count = Split(whole_line, ",")(1)
End If
Loop
infile.Close()
Return vote_count
End Sub

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