Marilee
Marilee

Reputation: 1598

Casting type streamreader to string

I have a list containing the following: name, initial, and age of a person, as in:

White, J, 23

Boucher, M, 30

Coetzee, G, 23

I'm trying to do the following:

Create a function that expects two parameters: parameter 1 is an integer called Age, parameter 2 is a string called fileName that takes in a filename on disk.

The function takes in the age from a textbox and filename statically typed into a second textbox (e.g. C:\nameList.txt)

The function should scan/read the file specified, and make a count of all persons having the same age. I.e. if 23 was typed into the textbox, "2" will be displayed, since 2 people are 23 in the above example.

Now I'm trying to do this using the following logic:

  1. I'm using streamreader to read the text file and assign all words in the file as a single string to variable.
  2. I will then split the string variable into many elements of an array
  3. I will then loop over the textArray using an if-else statement to check if the index of the array matches the age to check for variable.
  4. If match is found then increment counter variable to 1

In theory this is simple but I am having some problems with step 1. Here is my code for step 1:

        Function countAges(ByVal age As Integer, ByVal fileName As String) As Integer

        'Get Info From File'
        Dim textString As StreamReader
        textString = New StreamReader(fileName)
        textString.ReadToEnd()
        textString.Close()

        'index words to array'
        Dim allTextArray() As String
        allTextArray = textString.split 'HERE IS THE PROBLEM'

When trying to split the text which I got from the streamreader in textString variable I get the error Split is not a member of system.IO.

Question:

Please keep in mind I am new to VB when answering.

Upvotes: 0

Views: 4863

Answers (1)

Guffa
Guffa

Reputation: 700322

You are reading the contents of the file and just throwing it away. The ReadToEnd method doesn't store the data from the file somewhere internally in the reader, it returns it as a string.

Put the string in a variable:

Dim textString As StreamReader
textString = New StreamReader(fileName)
Dim text as String = textString.ReadToEnd()
textString.Close()

Now you can use the string:

allTextArray = text.split

(Perhaps also renaming textString to something that better represents what it really is, as it's not a string but a StreamReader.)

Upvotes: 1

Related Questions