maky55 maky55 - 17 days ago 10
Vb.net Question

writeToFile.WriteLine backspace?

I want to write some text to a .txt file, this is what I have, and it works mostly:

If System.IO.File.Exists(sListItems) = True Then

Dim writeToFile As New System.IO.StreamWriter(sListItems, True)

writeToFile.WriteLine(vbCrLf & txtGameTitle.Text)
writeToFile.Close()

Else

MsgBox("Error!")

End If
End If


The problem is with that, when I enter text such as 'Hello', it would instead put into the txt file 'Hello ' (with a space). Is there anyway to resolve this?

Answer

Don't use File.Exists(). It's a race condition waiting to blow up, and it's slower. Instead, look for the FileMode that matches how you want to use the file; then handle the exception if it fails (you need to handle the exception anyway, because of the race condition potential mentioned earlier).

Additionally, if you have your Using blocks correct, you don't need to call .Close().

Try
    Using fs As New FileStream(sListItems, FileMode.Open)
        fs.Seek(0, SeekOrigin.End)
        Using sw As New StreamWriter(fs)
            sw.WriteLine(txtGameTitle.Text)
        End Using
    End Using
Catch ex As IOException
    MsgBox("Error! -- " & ex.Message)
End If

But I wonder if you really care that the file already exists, and all you really need to do is this:

File.AppendAllText(sListItems, txtGameTitle.Text)