"TechieMom" <me********@gmail.com> wrote in message news:11**********************@g44g2000cwa.googlegr oups.com...
I have the following code:
Dim oFile As Stream
Dim oReader As StreamReader
Dim strCarName
oFile = [Assembly].GetExecutingAssembly.GetManifestResourceStream("A ssignment3.Vehicles.txt")
oReader = New StreamReader(oFile)
For Each strCarName In oReader.ReadLine
lstCarSpecs.Items.Add(strCarName)
Next
When it reads the text file it reads only the 1st line and displays it
as follows:
B
o
n
n
e
v
i
l
l
e
I thought the readline would read until a carriage return.
It does, but you're treating ReadLine as if it returns a
collection of strings. It doesn't, it returns just one string.
And because you haven't specified the type of strCarName
it's being treating as a Char type since a string is collection
of Chars--so you're effectively looping through each
character of the one string.
Also, remember to initialise all variables before using
them. Normally you'd initialise them to Nothing.
Finally, file processing should employ structured
error-trapping (Try..Catch...Finally).
Amend your code as follows:
' Initialise variables
Dim oFile As Stream = Nothing
Dim oReader As StreamReader = Nothing
Dim strCarName As String = Nothing
Try
' Open streams -- may cause exception
oFile = [Assembly].GetExecutingAssembly.GetManifestResourceStream("A ssignment3.Vehicles.txt")
oReader = New StreamReader(oFile)
' If you get this far, the streams are open
' and can be processed.
' Peek the next character in the file (don't
' process it). If it's (-1) you've reached the
' end of the file, otherwise keep reading
' strings.
While oReader.Peak > (-1)
strCarName = oReader.ReadLine
lstCarSpecs.Items.Add(strCarName)
End While
Catch Ex as System.Exception
' Handle errors
' E.g, display a friendly message.
Finally
strCarName = Nothing
End Try
Try
' oReader may not be open
oReader.Close()
Catch Ex As System.Exception
' Ignore error
Finally
oReader = Nothing
End Try
Try
' oFile may not be open
oFile.Close()
Catch Ex As System.Exception
' Ignore error
Finally
oFile = Nothing
End Try
' Note: The Finally clauses are optional.
' Garbage collection will take care of
' tidying up for you, but it's best to do
' your own cleanup. It's simply good
' programming etiquette.