How to insert, if there is search and replace can't find required string via regular expressions in vb.net

I am using this match pattern
"^(user_pref\(\s*""browser\.startup\.homepage"",\s*"")[^""]*("")"

Open in new window


to find this string
user_pref("browser.startup.homepage", http://www.google.com");

Open in new window

and replace with my own.

Sometimes what happens, this string is not present in file and therefore i can't be searched and replaced, in that condition i want to insert one string of my own
user_pref("browser.startup.homepage", http://www.google.com");

Open in new window

but also have to make sure if string is already present then it should be replaced instead of inserting. because if unproperly done it will leave two strings.

I actually don't know proper syntax to do stream reader and write the thing in vb.net so unsure whether this thing comes under regular expressions or streaming.
LVL 3
herit02Asked:
Who is Participating?
 
käµfm³d 👽Connect With a Mentor Commented:
Try this:
Dim yourString As String = "your replacement strign"
Dim pattern As String = "^(user_pref\(\s*""browser\.startup\.homepage"",\s*"")[^""]*("")"
Dim yourFilename As String = "yourfilename.txt"

Dim found As Boolean = False
Dim temp As String = System.IO.Path.GetTempFileName()

Using reader As New System.IO.StreamReader(yourFilename)
    Using writer As New System.IO.StreamWriter(temp)
		While Not reader.AtEndOfStream
			Dim m As System.Text.RegularExpressions.Match
			Dim line As String = reader.ReadLine()

			m = System.Text.RegularExpressions.Regex.Match(line, pattern)

			If m.Success Then
			    found = True
			    
			    line = System.Text.RegularExpressions.Regex.Replace(line, pattern, yourString)
			End If
			
			writer.WriteLine(line)
		End While
		
		If Not found Then
		    writer.WriteLine(yourString)
		End If
	End Using
End Using

System.IO.File.Move(temp, yourFilename)

Open in new window

0
 
bergergeCommented:
Hello Herit02,

I suggest to flatly remove an existing line with the prefix    user_pref("browser.startup.homepage"
with the search-pattern
 "^(user_pref\(\"browser\.startup\.homepage"

After the removal you now can add the desired line without the fear of duplicate lines:
user_pref("browser.startup.homepage", http://www.anysearchengine.com");

Kind regards
George
0
 
herit02Author Commented:
Dear kaufmed,
Actually i am pretty bad at stream writing and reading, i tried my best but getting some errors, so could you merge your solution into following code. if possible for you, keep the variables intact in the way i assigned them.
I have regex.replace code so you just add a few lines to find match and insert if nothing get found.

   Private Sub performtask()
        Dim fso, inputFile, outputFile
        Dim str As String
        Dim myFile As String = "c:\configuration.txt"
        fso = CreateObject("scripting.filesystemobject")
        inputFile = fso.OpenTextFile(myFile, 1)
        str = inputFile.ReadAll
        Dim found As Boolean = False
        Dim joiner As String = "$1" & TextBox1.Text & "$2" 'textbox1 contains http://www.somewebsite.com
        Dim replacementstring As String = joiner
        Dim matchpattern As String = "^(user_pref\(\s*""browser\.startup\.homepage"",\s*"")[^""]*("")"
        'here comes the actual replacement. 
        str = Regex.Replace(str, matchpattern, replacementstring, RegexOptions.Multiline)
        outputFile = fso.CreateTextFile(myFile, True)
        outputFile.Write(str)
        MsgBox("Done")
   End Sub

Open in new window

0
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

 
käµfm³d 👽Commented:
Is this VB.NET, or VBA? If .NET, why in the world are you using

    CreateObject("scripting.filesystemobject")

There are already classes built into .NET to perform reading of files. You should not need to rely on CreateObject for such things.
0
 
herit02Author Commented:
i don't much about these, but this was how i received the code.
neway could you try adding your solution into this existing one?
if require you may remove create object and use inbuilt class.
thanks so much for helping me out!
0
 
herit02Author Commented:
i tried your way
but its giving me following error
"AtEndOfStream is not a member of system.io.streamreader"
0
 
käµfm³d 👽Commented:
>>  "AtEndOfStream is not a member of system.io.streamreader"

That's my fault--the correct property is "EndOfStream". That's what I get for trying to code from memory  = )
0
 
herit02Author Commented:
when i go by that method, it gives exception that file is already in use.
i troubleshooted 5-10 times whether any process was using it but no process was.
kaufmed, it would be very grateful of you if you could implement yourself your solution in to mine.

0
 
käµfm³d 👽Commented:
Which file (or which line of code) is generating the exception?
0
 
herit02Author Commented:
"Using writer As New System.IO.StreamWriter(yourFilename)"
0
 
käµfm³d 👽Commented:
That's incorrect. Look at lines 8 & 9 in post http:#34952048 . The reader should point to "yourfilename" and the writer should point to "temp".
0
 
herit02Author Commented:
i actually tried with temp too.
ok re-tried for confirmation with using temp but it gives error that the file already exists and then it does not allow to move.
0
 
herit02Author Commented:
It goes to last line when it actually replaces temp file with original one,
and this error comes
Cannot create a file when that file already exists.
0
 
käµfm³d 👽Connect With a Mentor Commented:
Let's use Copy() instead of Move(). Copy() optionally takes a third parameter specifying whether or not to overwrite existing files:
System.IO.File.Copy(temp, yourFilename, true)

Open in new window

0
 
herit02Author Commented:
Hey thanks so much for helping me out.
It really did solved problem finally...

btw why it didn't allowed me when we used move and replace instead of copy and replace


Cheers!,
Herit
0
 
käµfm³d 👽Commented:
>>  btw why it didn't allowed me when we used move and replace instead of copy and replace

I believe it's by design. I thought Move() had an overload to specify overwrite, but I was mistaken. This is why I suggested the use of Copy() instead.

Glad to help  : )
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.