Question Removing 1 line from a text file

mattkw80

Well-known member
Joined
Jan 3, 2008
Messages
49
Location
Ontario, Canada
Programming Experience
Beginner
Hi Guys,

I'm really stuck on something, which, is probably easy, but I've blown hours trying to figure this out.

I need to be able to remove 1 line from a textfile. I will always know exactly what line it is, as, it's the same "string" as a variable. So if my variable is called "removeThis" then I need to be able to Read through the textfile, find the line that is equal to the removeThis string variable, and then rewrite the whole textfile.

Can someone help me through this?
 
I've done similar before in VB6.
I needed to replace a string in the text with something else.

I'm sure you can use the
VB.NET:
Public Function Replace(ByVal Expression As String, _
                 ByVal Find As String, _
                 ByVal Replacement As String, _
                 Optional ByVal Start As Integer = 1, _
                 Optional ByVal Count As Integer = -1, _
                 Optional ByVal Compare As Microsoft.VisualBasic.CompareMethod = Binary) As String
to replace the string you want for an empty string and then re-write the whole file.

I'm not sure if this is the best way to do it, I reckon it might just works.
 
Here's a small snippet showing how to read the contents of the file, remove unnecessary lines and write the contents back to the file.

VB.NET:
        Dim searchTerm As String = "Kentucky"
        Dim fullFilePath As String = "C:\Temp\states2.txt"

        Dim validLines As String() = (From line In IO.File.ReadAllLines(fullFilePath)
                                     Where Not line.Contains(searchTerm)).ToArray

        Using sw As New IO.StreamWriter(fullFilePath)
            sw.Write(String.Join(Environment.NewLine, validLines))
        End Using
 
Back
Top