reading txt file separate by char each item?

simplest way to separate items by char?

Page 1 of 1

1 Replies - 3407 Views - Last Post: 10 December 2008 - 12:35 AM Rate Topic: -----

#1 XMEGA  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 135
  • Joined: 17-November 08

reading txt file separate by char each item?

Posted 09 December 2008 - 10:04 PM

I woud like to know the most easy and simpliest way I would go about doing this say I have a text file and it contains

Bob, 24
Joe, 10

I want to read it and put it into a listbox separating by the "," or just being a newline ect. So my listbox would look like this (doing both methods)

"Bob"
"24"
"Joe"
"10"

or just the newline method way

"Bob, 24"
"Joe, 10"

I know how to read files like so
		Dim contents As String
		contents = My.Computer.FileSystem.ReadAllText("ReadIt.txt")



and know how to display its contents in a listbox and label like so

		xReadingListBox.Items.Add(contents)
		xReadingLabel.Text = contents



what I would really like to kno is to read a text file in and separate by any 1 char being ("," or ":" or ect...) sending the text befor the char to 1 list box and sending the text after the char to another list box say you had names and numbers the first listbox would have all the names while the second listbox would have the numbers ect...

This post has been edited by XMEGA: 09 December 2008 - 10:12 PM


Is This A Good Question/Topic? 0
  • +

Replies To: reading txt file separate by char each item?

#2 n8wxs  Icon User is offline

  • --... ...-- -.. . -. ---.. .-- -..- ...
  • member icon

Reputation: 972
  • View blog
  • Posts: 3,878
  • Joined: 07-January 08

Re: reading txt file separate by char each item?

Posted 10 December 2008 - 12:35 AM

I wouldn't use My.Computer.FileSystem.ReadAllText() as it copies everything to one string, making it harder to parse. IMHO :)

I would rather use a StreamReader and read the file line by line into an ArrayList. Then each line in the ArrayList can be split as desired. Here is an example
Dim arrayList As New ArrayList
Dim line As String

Try
	Dim sr As StreamReader = New StreamReader("ReadIt.txt")

	While sr.Peek() >= 0
		arrayList.Add(sr.ReadLine())

	End While

	sr.Close()

Catch Ex As Exception
	MessageBox.Show(Ex.Message, "Something went wrong!!")
End Try

For Each line In arrayList
	Dim tmp() As String = Split(line)

	// do whatever with the split strings

Next


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1