Delete line from text file

dwyane123

Member
Joined
Oct 14, 2008
Messages
23
Programming Experience
Beginner
Hi can you all help me on how to delete line from a text file?

for example

abc1
abc2
abc3

user will choose from a list box the items to delete. if chosen, it will delete off the line

if abc2 is deleted,

it will end up becoming
abc1
abc3

Any idea how? in vb.net language thanks alot :)
 
You can't actually delete a line from a text file. You simply have to read in the file and then write it out again, minus the line you don't want. You have two main options:

1. Read the whole file in, remove the line locally and then write the whole file back out again.

2. Read the file in line by line and write out each line as you read it unless it's the one you want to remove.

The second option is a bit of a hassle as you cannot write to the same path as you read from. As such you'd have to delete the entire file once you'd finished reading it and then move the file you wrote to back to that location. The first option is generally the better, although it will use a lot of memory if the file is large. Assuming you go for the first option, here's the easiest way:
VB.NET:
Dim lines As New List(Of String)(IO.File.ReadAllLines("file path here"))

'Remove the line to delete, e.g.
lines.RemoveAt(1)

IO.File.WriteAllLines("file path here", lines.ToArray())
How exactly you remove the line depends on how exactly you identify it, e.g. by index or by content.
 
VB.NET:
Dim lines As New List(Of String)(IO.File.ReadAllLines("file path here"))
'Remove the line to delete, e.g.
lines.RemoveAt(1)
IO.File.WriteAllLines("file path here", lines.ToArray())
.
How can I delete/remove a specific line that I know as StartWith and its unique one in entire text file I am sure there is not any duplicate line StartWith the same?
 
I figured out the issue's matter and resolved it

The event of DeleteToolStripMenuItem at ContextMenuStrip works well with my Remove sub.
Sub MySubRemove()
        Dim line As String = Nothing
        Dim linesList As New List(Of String)(File.ReadAllLines(mytxtFile))
        Dim SR As New StreamReader(mytxtFile)
        line = SR.ReadLine()
        For i As Integer = 0 To linesList.Count - 1
            If line.StartsWith(strRemove) = True Then
                SR.Dispose()
                SR.Close()
                linesList.RemoveAt(i)
                File.WriteAllLines(mytxtFile, linesList.ToArray())
                Exit For
            End If
            line = SR.ReadLine()
        Next i
    End Sub


Private Sub DeleteToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles DeleteToolStripMenuItem.Click
        strRemove = DataGridView1.CurrentRow.Cells(0).Value.ToString
        DataGridView1.Rows.Remove(DataGridView1.CurrentRow)
        MySubRemove()
    End Sub
 
Back
Top