0

I have as csv file with a header. I need to loop through all of the lines in the csv and on each one append an additional column at the very end. I would like to not have to read the line in each because when it gets re-written it seems to change data. I have a weird field with symbols so it doesn't read it right. I know this has to be easy but I have spent two days researching options, and have not found the answer. I am on a huge time crunch to get this finished up today. Any suggestions?

Thanks in Advance

  • 1
    Does it have to be with VB.Net?... Truly Excel might be even faster... Open it in Excel, add in the extra column and re-save as csv.... Just a different idea... – John Bustos Aug 14 '14 at 20:35
  • As another option, your streamreader can deal with different encodings which would stop the problem of your symbols being converted... Something like this: http://stackoverflow.com/questions/592824/c-sharp-help-reading-foreign-characters-using-streamreader – John Bustos Aug 14 '14 at 20:37
  • If you read and write to the same file at the same time it will cause problems. You could write into a temporary file and at the end overwrite the file. – the_lotus Aug 15 '14 at 13:36

1 Answers1

0

As suggested, if your data is getting mangled somehow then it's most likely an encoding issue. The answer to your problem is extremely simple, e.g.

Dim filePath As String
Dim encoding As Encoding
Dim newColumnHeader As String

'...

Dim lines = File.ReadAllLines(filePath, encoding)

lines(0) &= "," & newColumnHeader

For lineNumber = 1 To lines.GetUpperBound(0)
    lines(lineNumber) &= "," & lineNumber
Next

File.WriteAllLines(filePath, lines, encoding)
jmcilhinney
  • 50,448
  • 5
  • 26
  • 46