0

我想使用 c# 读取 php 文本文件。该文件如下所示:

2.20:2.20:2.20:2.20:2.20:
2012-07-12:2012-07-11:2012-07-10:2012-07-09:2012-07-08:

我想将所有行都添加到列表框。在实际情况中有六行,但首先我应该阅读这两行。我的代码:

void web_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
     try
     {
         int i;
         string price_line = "";
         string date_line = "";
         List<decimal> prices = new List<decimal>();
         List<string> dates = new List<string>();

         using (var reader = new StreamReader(e.Result))
         {
             price_line = reader.ReadLine();
             date_line = reader.ReadLine();
             string[] bit_1 = price_line.Split(':');
             string[] bit_2 = date_line.Split(':');
             for (i = 0; i < 2; i++)
             {
                 prices.Add(decimal.Parse(bit_1[i]));
                 dates.Add(bit_2[i]);
             }
             listBox1.ItemsSource = prices;
             listBox2.ItemsSource = dates;
         }
     }
     catch
     {
          MessageBox.Show("Can't read!");
     }           
}

现在我得到“NullException”。如何解决这个问题?

4

1 回答 1

1

编辑:

这是关于什么的:

using (StreamReader reader = new StreamReader(e.Result)) 
{
     List<string> lines = new List<string>();
     while (!reader.EndOfStream) 
         lines.Add(reader.ReadLine());

     string prices = lines.First().Split(':');

     List<decimal> listPrices = new List<decimal>();
     List<string> listDates = lines.Last().Split(':').ToList();

     foreach(string s in prices)
        listPrices.Add(double.Parse(s));

     listBox1.ItemsSource = listPrices;
     listBox2.ItemsSource = listDates;
}

你应该检查 if e.ResultlistBox1并且listBox2不为空。

于 2012-07-20T17:56:45.147 回答