开发者

VB.Net - Writing to textfile from a textbox

Hey guys, just another little problem here! Trying to write a quiz for a college portfolio and having trouble with writing to a .txt textfile. On one form(form4.vb), I have a listbox that picks up the information held within a notepad textfile called "usernames" which contains names of quiz users. When written in manually to this textfile, my listbox picks it up fine, however, on a different form(form3.vb), I have a textbox where a user inputs their name, this is supposed to go to the "usernames.txt" textfile to be picked u开发者_如何学Cp by the listbox on the other form but instead, it does not write anything at all and if there is already text on this textfile, it wipes it all out. I also have to use the application.startup path instead of the usual C:\my documentents\ etc so i would have to begin with something like this: (Note: code is a little mixed up due to messing around with different variations but this is just a example)

    'Try
    '    Dim appPath As String
    '    Dim fileName As String

    '    appPath = Application.StartupPath
    '    fileName = appPath & "\usernames.txt"
    '    sWriter = New System.IO.StreamWriter(fileName)

    '    sWriter.Close()
    '    MessageBox.Show("Writing file to disk")

    'Catch ex As Exception
    '    MessageBox.Show("File Access Error", "Error")

    'End Try
    'MessageBox.Show("Program terminating")

    'Application.Exit()

Hope someone can help! =)


You want something more like this:

Dim appPath As String = Application.StartupPath
Dim fileName As String = IO.Path.Combine(appPath, "usernames.txt")

Try
    IO.File.AppendAllText(fileName, TextBox1.Text & Environment.NewLine)
Catch ex As Exception
    MessageBox.Show("File Access Error", "Error")
End Try
MessageBox.Show("Program terminating")

Environment.Exit()

Some things worth noting in this code:

  • Path.Combine() as the correct way to add the separator character
  • File.AppendAllText() is much easier for simple things than messing with streamreader/writer. Pair it with File.ReadAllText() or File.ReadAllLines() in the other direction.
  • Environment.Exit() vs Application.Exit()


Where is your dim statement for sWriter (streamWriter)?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜