Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Write to a specific line in a textfile

Status
Not open for further replies.

flybravo

Programmer
Jun 30, 2003
35
US
Does any one know how to write a line of text to a specific line. I need to be able to update any line at any giving time.

 
Hi,

If you are not changing the length of the line, you might be better of by just replacing the relevant bytes in the file. But in most cases you need to change the length of the line and therefore move the bytes for the rest of the file on the disk. The easiest way to do that is to read the entire file into an array, manipulate the array and write it to the file agian:
-----------------------------------------------
Private Function ChangeLine(ByVal FileName As String, ByVal LineNo As Int32, ByVal NewValue As String) As Boolean
Dim SR As New IO.StreamReader(FileName)
Dim FileArr() As String = Split(SR.ReadToEnd, vbCrLf)
SR.Close()
If UBound(FileArr) >= LineNo Then
FileArr(LineNo) = NewValue
ChangeLine = True
Dim SW As New IO.StreamWriter(FileName)
SW.Write(Join(FileArr, vbCrLf))
SW.Close()
Else
ChangeLine = False
End If
----------------------------------------------

Sunaj
'The gap between theory and practice is not as wide in theory as it is in practice'
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top