שתף באמצעות


VB.NET Find text in file and get line number

Question

Wednesday, January 22, 2014 5:04 AM

Hi, I'm kinda a "not-so-good-programmer" so please keep the answers understandable.

So, I have a text file like this:

Name:Dave
Setting1:abc
Setting2:abcdefg

So, I want to change the line with "Setting1:" but leave the other text untouched. And there maybe other settings there, so the code has to scan for "Setting1:" but change the whole line into "Setting1:123" or just change the text after it. And then save the text file.

Thanks in advance,

David Wu

All replies (3)

Wednesday, January 22, 2014 5:19 AM ✅Answered

Hi, please try:

Dim lines = System.IO.File.ReadAllLines("c:\1.txt")
        For i = 0 To lines.Length - 1
            If lines(i).StartsWith("Setting1:") Then
                lines(i) = "Setting1:123"
            End If
        Next
        System.IO.File.WriteAllLines("c:\1.txt", lines)

Or

   Dim text = System.IO.File.ReadAllText("c:\1.txt")
        text = text.Replace("Setting1:abc", "Setting1:123")
        System.IO.File.WriteAllText("c:\1.txt", text)

Wednesday, January 22, 2014 5:21 AM ✅Answered

Please use regular Express to find out the specific fixed word, do changing and upgrate to your file:

Dim reg As New Regex("Setting1:.+")
        Dim contents As String = IO.File.ReadAllText("c:\TextFile1.txt")
        contents = reg.Replace(contents, "Setting1:abcdefg" & vbCrLf)
        IO.File.WriteAllText("c:\textfile1.txt", contents)

ASP.NET Questions
Other Discussions
FreeRice Donate
Issues to report
Free Tech Books Search


Wednesday, January 22, 2014 5:22 AM ✅Answered

So, I want to change the line with "Setting1:" but leave the other text untouched. And there maybe other settings there, so the code has to scan for "Setting1:" but change the whole line into "Setting1:123" or just change the text after it. And then save the text file.

You can read all lines in the file into an array of string.  See:
http://msdn.microsoft.com/en-us/library/s2tte0y1(v=vs.110).aspx

Then you can scan the items in the string array searching for the one you want.  In your example you would use the StartsWith method to identify the array element you are after.  See:
http://msdn.microsoft.com/en-us/library/baketfxw(v=vs.110).aspx

Then you can split the string at the colon using the Split method:
http://msdn.microsoft.com/en-us/library/6x627e5f(v=vs.90).aspx

Create the new string from the array element (0), a colon and your literal, put it back into the array, and write the whole array:
http://msdn.microsoft.com/en-us/library/s2tte0y1(v=vs.110).aspx