read line of text

Timbo292832

Member
Joined
Apr 7, 2013
Messages
5
Location
Nsw Australia
Programming Experience
Beginner
hi guys
i want to read a line of text from a text file
just one line (it will contain one word)

what i want to do is read the second line and hold it in a string
also i would want to modify the second line in a file

i am able to readalltext but i just want to read and write one line

could anyone please give me an example
 
Unless you know for a fact that the binary form of the text you're replacing is exactly the same length as the binary form of the text you're replacing it with (which would be a rare thing) you can't just edit a text file in place. You almost always have to read the whole lot in and then write the whole lot back out again. If it's a small file then the best option is to read the whole lot into memory, edit it, then write the whole lot out again, e.g.
Dim lines = File.ReadAllLines(filePath)

'Edit the second line.
lines(1) = "new text here"
File.WriteAllLines(filePath, lines)
Where ReadAllText reads the entire file contents into a single String, ReadAllLines reads the lines of the file into a String array.

If the file might be large then it's not a good idea to store the whole thing in memory at the same time. In that case, you can read the file line by line and write it out to a temp file, editing as you go. When you're done, you can move the temp file and overwrite the original file, e.g.
Dim tempFilePath = Path.GetTempFileName()

Using reader As New StreamReader(filePath),
      writer As New StreamWriter(tempFilePath)
    Dim lineIndex = 0

    Do Until reader.EndOfStream
        Dim line = reader.ReadLine()

        If lineIndex = 1 Then
            line = "new text here"
        End If

        writer.WriteLine(line)
        lineIndex += 1
    Loop
End Using

My.Computer.FileSystem.MoveFile(tempFilePath, filePath, True)
or, from .NET 4.0:
Dim tempFilePath = Path.GetTempFileName()

Using writer As New StreamWriter(tempFilePath)
    Dim lineIndex = 0

    For Each line In File.ReadLines(filePath)
        If lineIndex = 1 Then
            line = "new text here"
        End If

        writer.WriteLine(line)
        lineIndex += 1
    Next
End Using

My.Computer.FileSystem.MoveFile(tempFilePath, filePath, True)
 
Back
Top