2

I'm making a program that lets you add student info to an existing CSV text file but whenever I use append text it adds the new info to part of the last line and then a new line.

I want it to do this:

John Doe,29,Male

John Doe,29,Male

It does this instead:

John Doe,29,MaleJo

hn Doe,29,Male

Note: there isn't actually an empty line between each set of info, I just wanted it to be easy to read when I posted it here.

Here is the code for that section:

Dim swVar As IO.StreamWriter = IO.File.AppendText(frmMain.fileName)

swVar.WriteLine(txtName.Text & "," & txtAge.Text & "," & gender)

swVar.Close()

Any help would be appreciated, thanks!

Community
  • 1
  • 1
  • Is the method that does this being called by multiple threads? I suspect that it's being called while it's already in the middle of writing one entry and a second gets inserted in the middle – Steven Doggart Dec 05 '13 at 21:36
  • Other than that, the code you showed works fine for me when I tested it. – Steven Doggart Dec 05 '13 at 21:37

2 Answers2

0

A handy tool in VS2010 (and others) is snippets - right click Insert Snippets... - lots of code patterns for typical tasks. In your case here is a modified snippet:

Sub AddToFile(textToAdd As String, filePath As String)
    My.Computer.FileSystem.WriteAllText(filePath, textToAdd, True)
End Sub

You may want to check/add a vbNewLine to the text being added since one is not automatically added as with WriteLine.

Not a direct reply to your stated problem, but an alternate method.

rheitzman
  • 2,247
  • 3
  • 20
  • 36
0

See if something like this works better:

IO.File.AppendText(frmMain.fileName, vbNewLine & txtName.Text & "," & txtAge.Text & "," & gender & vbNewLine)

AppendText will open write and close all in one operation so there's no need for a separate streamwriter. It also doesn't add newlines so those must be added separately

Unless of course you are doing a series of writes to the same file then something like this would probably be more appropriate:

Dim swVar As New IO.StreamWriter(frmMain.fileName, True)
'write your lines here
swVar.WriteLine(txtName.Text & "," & txtAge.Text & "," & gender)

swVar.Close()
tinstaafl
  • 6,908
  • 2
  • 15
  • 22