I'm working on a program which should edit a text file by adding/deleting some specific lines.
By default this text file doesn't have these specific lines, so the program will add them.
But I also want it to replace them if they're already in the text file.
Basically this is my idea:
- Read the text file
- Search the specific lines
- If they exist then replace them
- Else add them
I pretty much know how to read a text file, how to search for specific lines, how to replace them and how to add them, but I don't know or can't figure it out how to know the "if they exist".
I need something like "If String1.Exists = True Then..." (I know it's completely wrong, but I hope it helps you to help me).
I hope I've been clear, if not tell me I'll try my best. :)
This is part of the source code of the program
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim textfile As String = "C:\test.txt" If System.IO.File.Exists(textfile) Then 'Read the text file' Dim lines = IO.File.ReadAllLines(SettingsFile) Dim string1 As Integer = Array.FindIndex(lines, Function(s) s.Contains("adf100009")) Dim string2 As Integer = Array.FindIndex(lines, Function(s) s.Contains("adf100010")) 'Here should be an If string1.exists = true then...' 'Replace the lines if found' Dim tempList As New List(Of String)(lines) tempList.RemoveAt(string1) tempList.RemoveAt(string2) tempList.Insert(string1, "adf1000" & inputvalue1) tempList.Insert(string2, "adf1000" & inputvalue2) lines = tempList.ToArray IO.File.WriteAllLines(SettingsFile, lines) MsgBox("Lines replaced") Else MsgBox("Cannot find the Text File") End If
It's far from being perfect and complete. Just to give you an idea on what I'm working on. :)
Thanks for the attention.