cake2 cake2 - 3 months ago 16
Vb.net Question

Visual Basic 2013 Text duplicating

I had issues with a program, so
I was making a notepad program for my XP overlay thingy, and whenever I reopen it twice, the text is duplicated.

For example when I type in

test


and i reopen it second, it outputs:

testtest


I have no idea what is causing this, but it certainly is annoying.
If I could get some help with this issue that would be awesome!
Heres my code:

Private Sub notepad_X_Click(sender As Object, e As EventArgs) Handles notepad_X.Click

Try
My.Computer.FileSystem.WriteAllText("C:\XP\notepad.txt", RichTextBox1.Text, True)
RichTextBox1.Text = ""
Catch Exc As System.IO.DirectoryNotFoundException
My.Computer.FileSystem.CreateDirectory("C:\XP")
End Try

notepad.Enabled = False
notepad.Visible = False
End Sub

Private Sub Notepad_btn_Click(sender As Object, e As EventArgs) Handles StartM_Notepad.Click
RichTextBox1.Text = ""
Try
RichTextBox1.Text = My.Computer.FileSystem.ReadAllText("C:\XP\notepad.txt")
Catch Exc As System.IO.DirectoryNotFoundException
My.Computer.FileSystem.CreateDirectory("C:\XP")
End Try
notepad.Enabled = True
notepad.Visible = True

End Sub

Answer

This happens because you have explicitly specified it to do so. You are using the FileSystem.WriteAllText() overload with 3 parameters, where you've set the third parameter to True. That parameter (called append) specifies if you want to append text to your file or overwrite it.

As you've told it to append text to your file it will just write the new text you give it (whatever's in RichTextBox1) after the already existing text. Set the parameter to False so that the text gets overwritten instead:

My.Computer.FileSystem.WriteAllText("C:\XP\notepad.txt", RichTextBox1.Text, False)
Comments