Reputation: 39
How can I in VB get and output, separated by a comma, each line of a file EXCEPT the last line?
Here is my code:
Dim ofd As New OpenFileDialog
ofd.FilterIndex = 1
If ofd.ShowDialog = Windows.Forms.DialogResult.OK Then
TextBox13.Text = ofd.FileName
Else : Exit Sub
End If
For Each line In IO.File.ReadLines(TextBox13.Text)
TextBox5.Text = line + ", "
Next
End If
An example:
line1
blabla
asdfghj
Output in textbox5:
line1, blabla, asdfghj
And NOT
line1, blabla, asdfghj,
Upvotes: 1
Views: 144
Reputation: 25013
You could use String.Join like this:
TextBox5.Text = String.Join(", ", IO.File.ReadLines(TextBox13.Text))
which automatically does not append the last separator.
Edited to add: Please note that as a matter of readability, and hence maintainability, you should not try to do too many things in one line. It is not quite pushing it for that one line, but if I were, say, to be constructing a path to the file as well, I would use a separate line with another variable to hold the result of Path.Combine rather than writing it all in one big line.
Upvotes: 2
Reputation: 218798
Instead of putting the values directly in the TextBox
, first put them in a collection:
Dim lines As New List(Of String)
For Each line In IO.File.ReadLines(TextBox13.Text)
lines.Add(line)
Next
Or, even simpler...
Dim lines = IO.File.ReadLines(TextBox13.Text)
Then once the collection is populated, use String.Join
to join it by your separator:
TextBox5.Text = String.Join(", ", lines)
Upvotes: 1