0867532
0867532

Reputation: 15

Scan text file for line containing a given string and replace the line with another string

I want to scan my file for line that contains a particular string "black=" and if there is a match replace it with "blah blah" but I don't know how to do that. Here is what I tried but it does not work.

Dim myStreamReaderL1 As System.IO.StreamReader
myStreamReaderL1 = System.IO.File.OpenText("C:\File.txt")
myStreamReaderL1.ReadLine()
If myStreamReaderL1.ReadLine.Contains("black=") Then
    Button2.Hide()
Else
    Return
End If

Upvotes: 0

Views: 19326

Answers (1)

George
George

Reputation: 2213

Assuming the input file is not huge, you can read the whole file into a string and change all instances of black= to blah blah

        Dim myStreamReaderL1 As System.IO.StreamReader
        Dim myStream As System.IO.StreamWriter

        Dim myStr As String
        myStreamReaderL1 = System.IO.File.OpenText("C:\File.txt")
        myStr = myStreamReaderL1.ReadToEnd()
        myStreamReaderL1.Close()


        myStr = myStr.Replace("black=", "blah blah")
        'Save myStr
        myStream = System.IO.File.CreateText("C:\FileOut.txt")
        myStream.WriteLine(myStr)
        myStream.Close()

EDIT: a slightly more efficient (less code) version with ReadAllText per Christian Sauer 's suggestion.

EDIT2: if I am trying to be efficient, lets optimize everything. One line is enough, me thinks.

If you want to save into a file:

        System.IO.File.WriteAllText("C:\FileOut.txt", System.IO.File.ReadAllText("C:\File.txt").Replace("black=", "blah blah"))

If you simply want to store into a string to be used later:

        Dim myStr As String = System.IO.File.ReadAllText("C:\File.txt").Replace("black=", "blah blah")

Upvotes: 3

Related Questions