streamreader

ThePentiumGuy

Well-known member
Joined
May 21, 2003
Messages
1,113
Location
Boston, Massachusetts
hey

i have this code to read text from a textfile with StreamReader
what i want to do is:

- be able to sort out each CHARACTER - not line, the
streamreader reads

- find out what line number i am currently reading

heres what i got

Code:
Imports System
Imports System.IO

the code below is in form1.load

Dim srdr As StreamReader = New StreamReader("map/test/test.txt") 


        Dim ln String

        Do
            line = srdr.ReadLine()
            MessageBox.Show(ln)
        Loop Until ln Is Nothing

        srdr.Close()

thanks
 
If you are reading it a line at a time you could then keep track of the line count based on each readline and treat the string as a character array.

Code:
Dim srdr As StreamReader = New StreamReader("map/test/test.txt")

Dim LineCount As Integer
Dim ln As String

Do
	LineCount += 1
	ln = srdr.ReadLine()
	MessageBox.Show(ln)
	Dim ch() As Char = ln.ToCharArray

	For Each c As Char In ch
		MessageBox.Show(c.ToString())
	Next
Loop Until ln Is Nothing

srdr.Close()

or similar
 
Just my lazy naming convention;)
ch() is the string turned into an array of characters, c will contain an individual character. The for each c as char in ch just loops through them one character at a time.
The syntax is just a shorthand way of doing for each loops in VS.Net 2003

Code:
For Each c As Char In ch
        MessageBox.Show(c.ToString())
Next

same as 
dim c as char
for each c in ch
        MessageBox.Show(c.ToString())
Next
 
Last edited by a moderator:
oh vs.net 03 :-p ihave 02

i am experiencing 1 problem though
when it gets to the very end of the textfile,
Dim ch() As Char = ln.ToCharArray
gives an error:
An unhandled exception of type System.NullReferenceException occurred in RPG.exe

Additional information: Object reference not set to an instance of an object.

im guessing that since its at the very end, nothing is there it cannot convert it("nothing") to a char array

any suggestions? please help - thanks
 
You could use a try ... catch block around the line or just check it first

Code:
Dim srdr As StreamReader = New StreamReader("map/test/test.txt")

Dim LineCount As Integer
Dim ln As String

Do
    LineCount += 1
    ln = srdr.ReadLine()
    MessageBox.Show(ln)
    May be a bit of a nasty hack but should work.
    If ln.ToCharArray Is Nothing Then Exit Do
    
    Dim ch() As Char = ln.ToCharArray

    For Each c As Char In ch
        MessageBox.Show(c.ToString())
    Next
Loop Until ln Is Nothing

srdr.Close()
 
nice

i never knew you could "If ln.ToCharArray Is Nothing Then Exit Do"

so u can exit loops at anytime?
if u wanted to exit an If loop you would say Exit If rihgt?
- thers always something new you could learn :-d

thanks a lot man
 
Theres no such thing as an "If loop", but yes, you can exit any
type of loop by using Exit (name of loop).
 
Back
Top