2012-07-20 69 views
0

我想用c#讀取php文本文件。該文件看起來像:用C讀取文件#

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」。如何解決這個問題?

+13

在哪一行你會得到那個異常? – 2012-07-20 17:50:40

+1

'e.Error'的價值是什麼?我想猜測,如果有錯誤,那麼'e.Result'將爲空。 – Marlon 2012-07-20 18:02:02

+0

我可以閱讀第一行,如果我評論date_line及其東西,但現在我得到NullException,如果date_line在.. – user1108483 2012-07-20 18:06:08

回答

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; 
} 

您應該檢查是否e.ResultlistBox1listBox2不爲空。

+0

好的,非常感謝!我試試:) – user1108483 2012-07-20 18:02:51

+0

不客氣。我編輯了我的代碼。 – 2012-07-20 18:07:35

+0

好的。但也有另一個問題。我並沒有真正閱讀本地文件,但我發送參數數據與Web客戶端,然後PHP文件使SQL查詢和只是回聲數據。然後,我應該通過互聯網連接閱讀線路。這就是爲什麼我有e.result .. – user1108483 2012-07-20 18:18:03