简体   繁体   English

在Windows Phone 7中解析文本文件

[英]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): 我正在尝试在Windows Phone 7中解析和读取文本文件。这是文本文件的格式(实际上有44个条目):

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. 最后的最后一个消息框仅用于调试-我试图确保将所有城市都读入称为city的字符串数组中。 However, when I output the cities array, all I get is the last value in the text file, for all 44 entries. 但是,当我输出citys数组时,对于所有44个条目,我得到的只是文本文件中的最后一个值。

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. 您在城市数组的所有44个条目中为同一城市设置了44倍。
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. 删除城市上的for循环并保持手动增量var可以解决问题。 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. 添加了if语句以检查出界外索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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