0

so I have a program I'm working on and I need to read lines of a .ini file then write user-defined text to a certain line in that file. So far some of my code is:

Dim File As String = ".\TestFile.ini"
    Dim FileText As String
    Dim NewText As String = TextBox2.Text
    Dim lines() As String
    Dim separator() As String = {Environment.NewLine}
    Dim x As Integer = 0
    If My.Computer.FileSystem.FileExists(File) Then
        FileText = My.Computer.FileSystem.ReadAllText(File)
        lines = FileText.Split(separator, StringSplitOptions.RemoveEmptyEntries)
        While x < lines.Length()
            If lines(x).Contains("Nickname") Then
                lines(x) = "Nickname" & "=" & TextBox2.Text
            End If
            NewText = NewText & lines(x) & Environment.NewLine
            x = x + 1
        End While
        My.Computer.FileSystem.WriteAllText(File, NewText, False)
    Else
        MsgBox("File does not exist!")
    End If

The file I want to edit looks like this:

Don't edit this line
Don't edit this line
Don't edit this line
Don't edit this line
Nickname=test
Don't edit this line
Don't edit this line
Don't edit this line

I only want to edit this word "test" on the 4th line but the code I have does do this but also adds whatever I put in TextBox2 at the start of the file. Like this (assume I put HelloWorld in TextBox2):

HelloWorldDon't edit this line
Don't edit this line
Don't edit this line
Don't edit this line
Nickname=HelloWorld
Don't edit this line
Don't edit this line
Don't edit this line

Anyone know what's wrong with my code? Sorry I'm quite new to this.

LukeSC1993
  • 43
  • 1
  • 7
  • You initialize the variable NewText with `Dim NewText As String = TextBox2.Text`, by the way, ReadAllLines and WriteAllLines could help – Steve Jan 31 '15 at 19:03
  • Yeah I already initialized the NewText (3rd line of my code). Everything works i just wondered why it was adding the text that I put in TextBox2 to the start of the file – LukeSC1993 Jan 31 '15 at 19:44

1 Answers1

2
Line 3: Dim NewText As String = TextBox2.Text

Initializes NewText = "HelloWorld"

Then you added first line:

Line 14:  NewText = NewText & lines(0) & Environment.NewLine 

NewText now equals "NewWorld" & lines(0) & NewLine

Try Dim NewText = String.Empty for line 3.

JStevens
  • 2,090
  • 1
  • 22
  • 26