Darius47
Darius47

Reputation: 21

How to replace text string in a text file

I am new to vb.net and am trying to do something really simple. I have this code which reads certain line of text from .ini file.

Dim FilePath As String = Application.StartupPath & "\bin\userconfig.ini"
Dim text As String = IO.File.ReadAllText(FilePath)
Dim newText = text.Replace("UserName = ", TextBox_NewUser.Text)
IO.File.WriteAllText(FilePath, newText)

How do I make it replace that line of text after the "=" with something you type in TextBox_NewUser. As you can see with current code it just replaces the whole "UserName =" which I don't want.

That specific line of text in the .ini by default has this value:

"UserName = Unnamed"

So how do I make it replace just that "Unnamed" with something I type in TextBox_NewUser?

Any assistance will be most appreciated.

Upvotes: 1

Views: 2998

Answers (2)

Karen Payne
Karen Payne

Reputation: 5102

Here is another way to go about this, there are additional assertions that could be done e.g. the code below assumes the lines don't begin with spaces and if they did you would first do a trim on each line before using StartsWith etc.

Config file

Role = Moderator
UserName = xxxx
Joined = 09/23/1006

Code

Public Class Form1
    Private fileName As String =
        IO.Path.Combine(
            AppDomain.CurrentDomain.BaseDirectory, "userConfig.ini")
    ''' <summary>
    ''' assumes the file exist but does not assume there is text in
    ''' the text box.
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        If Not String.IsNullOrWhiteSpace(TextBox_NewUser.Text) Then
            Dim lines As List(Of String) = IO.File.ReadAllLines(fileName).ToList
            For index As Integer = 0 To lines.Count - 1
                If lines(index).ToLower.StartsWith("username") Then
                    lines(index) = String.Concat("UserName = ", TextBox_NewUser.Text)
                End If
            Next
            IO.File.WriteAllLines(fileName, lines.ToArray)
        End If
    End Sub
End Class

Sample project on Microsoft OneDrive, VS2013 https://onedrive.live.com/redir?resid=A3D5A9A9A28080D1!907&authkey=!AKQCanSTiCLP4mE&ithint=file%2czip

Upvotes: 0

F0r3v3r-A-N00b
F0r3v3r-A-N00b

Reputation: 3003

Dim newText = text.Replace("UserName = Unnamed", "UserName = " & TextBox_NewUser.Text)

Upvotes: 2

Related Questions