How to Write to a Certain Line in a File in VB

431 views Asked by At

I know how to write to a file, however, I want to be able to write to a certain line. I have a large csv file which has many lines.

I can only write to the last line (using the writeline) but I really want to write to line x of 50 lines.

How do I do this?

1

There are 1 answers

0
sblandin On BEST ANSWER

I don't know if you can write to a specific line in a file, but if you need to you can write your lines to a List then write the list to a file

    'Declare your list
    Dim lines As New List(Of String)

    For Each lineToWrite In YourLines
        If toInsert Then
            'In this way you insert a row at the specified index, but this will grow the list not overwrite.
            lines.Insert(indexToInsert, lineToWrite)
        ElseIf toOverwrite Then
            'In this way you overwrite the item at the specified index
            lines(indexToOverwrite) = lineToWrite
        Else
            'Or you can just append it
            lines.Add(lineToWrite)
        End If

    Next

    'This will write the file
    System.IO.File.WriteAllLines("c:\yourfile.txt", lines.ToArray())