Read from and write to a text file in

[b][red]This message was edited by soweyoung at 2004-7-23 8:10:53[/red][/b][hr]
Hello everyone,
I am working on a small program in which reads a line at a time from a text file and writes a new line back to the file.

What I am trying to do is that I read from a text file line by line and want to be able to write a new line at the every third line.
The code is below. Any comments would be appreciated.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim inputString As String
Dim sb As New StreamReader("C: est.txt")
Dim i As Long

i = 1
inputString = sb.ReadLine

While Not inputString Is Nothing
If i = 3 Then
'want to write a line of message to a file right at this position
i = 0
End If

i += 1
inputString = sb.ReadLine
End While
End Sub


  • [b][red]This message was edited by kainsworth at 2004-7-25 14:8:18[/red][/b][hr]
    There are many ways of doing this. Here is just one approach - I prefer to read from file into an array or collection, make any amendments and then rewrite the file to reflect the amendments.
    One version of code that will achieve this is as follows:
    ' At top of Form code
    Imports System.IO
    Imports System.Collections.Specialized

    ' The following code to be fired from an appropriate event:
    Dim MyFileText As New StringCollection ' A collection
    Dim Fstrm As FileStream = New FileStream("MyTextFile.txt", FileMode.Open)
    ' Instantiate the StreamReader and pass it the FileStream
    Dim StrmR As StreamReader = New StreamReader(Fstrm)
    ' Read the whole file into the collection
    While StrmR.Peek <> -1
    End While
    ' close the file.

    ' Edit the collection (every 3rd line)
    Dim i As Integer
    For i = 2 To MyFileText.Count - 1 Step 3
    MyFileText.Item(i) = "Replaced in Code"

    ' Kill the original file, then recreate it
    Dim FS As FileStream = New FileStream("MyTextFile.txt", FileMode.CreateNew)
    ' Write amended data block back to recreated file
    Dim sw As StreamWriter = New StreamWriter(FS)
    For i = 0 To MyFileText.Count - 1
    The above will not be everybody's preferred route, and some may think the StringCollection to be overkill, but it works for me. :-) If you add a decent level of exception handling to the core code, it is a fairly robust way of going about it.

  • Here's a simple explanation on how to read data from and write data to text file in
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!