### Replace Line in Texfile

Example of replacing a line in a textfile.
' Replaces an item in a file. An item is a full line. The line is searched for. If found, then content will be replaced.
' Parameter: Folder
' Parameter: File
' Parameter: New Item
' Parameter: Linenumber
`Public Sub ReplaceItemInFile(d As String, f As String, newitem As String, line As Int)
If line < 1 Then Return
line = line - 1
Dim l As List
l.Initialize
' Read the content of the file
Dim tr As TextReader
Try
' init the textreader and read content into the list
tr.Initialize(File.OpenInput(d, f))
l.AddAll(tr.ReadList)
tr.Close
Catch
Log("Read Text File: Error " & LastException.Message)
If tr.IsInitialized Then tr.Close
End Try
tr.Close
' Change the line. If item is empty then remove line else replace content
If newitem.Length = 0 Then
l.RemoveAt(line)
Else
l.Set(line, newitem)
End If
' Write the revised list to the file again
Dim tw As TextWriter
Try
tw.Initialize(File.OpenOutput(d, f, False))
tw.WriteList(l)
tw.Flush
tw.Close
Catch
Log("Write Text File: Error " & LastException.Message)
If tw.IsInitialized Then tw.Close
End Try
End Sub`

Changed: , Category: Files, File: T6C193M1394.htm, ID: 1394