简体   繁体   中英

Parsing text file in Windows Phone 7

I'm trying to parse and read a text file in Windows Phone 7. Here is the format of the text file (there's actually 44 entries):

Millbrae,37.600322,-122.386735
SFO,37.61636,-122.391027
San Bruno,37.638262,-122.416513
South SF,37.664264,-122.444043

And here is my code:

var foo=Application.GetResourceStream(new Uri("stations.txt", UriKind.Relative));
        StreamReader streamReader = new StreamReader(foo.Stream);
        string x;
        int k;

            while ((x = streamReader.ReadLine()) != null)
            {
                string[] items = x.Split(',');
                   for (k = 0; k < 43; k++)
                 {

                     cities[k] = (items[0]);

                 }//for*/
            }//while

            for (k = 0; k < 43; k++)
            {
                MessageBox.Show(cities[k]);
            }

The last message box at the end is just for debugging-I was trying to make sure I got all the cities read into the string array called cities. However, when I output the cities array, all I get is the last value in the text file, for all 44 entries.

Can anyone point out to me what I am doing wrong? I'm not sure how I read in the last city for every value. Thanks!

You set for 44 times the same city in all the 44 entry of the cities array.
Then you repeat the same pattern for the next line and stop on the last line. So you fill the array only with the last entry.

      k = 0;
      while ((x = streamReader.ReadLine()) != null) 
      { 
            string[] items = x.Split(','); 
            if( k <= 44)
            {
                 cities[k] = (items[0]); 
                 k++;
            }
        }//while 

Removing the for loop on the cities and keeping a manual increment var will do the trick. Of course I am assuming that the cities array is declare somewhere as

   string[] cities = new string[44]();

Added an if statement to check out of bound index.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM