2014-09-24 69 views
0

在我的Windows窗體應用程序中,我試圖獲取一個CSV文件,它作爲2列。第一次爲日期和第二次值。問題是我拿我的csv文件後,我得到一個error.It說字符串不被識別爲一個有效的日期時間。 這裏是我的代碼:如何獲取csv的日期列並將其用作圖表中的x軸?

  string dosyaAdi;         
      private void btnUpload_Click(object sender, EventArgs e)   
       { 
       try  
      { 

      DialogResult result = openFileDialog1.ShowDialog(); 

      if (result == DialogResult.OK) 
      { 
       dosyaAdi = openFileDialog1.FileName; 
      } 


      var reader = new StreamReader(File.OpenRead(dosyaAdi)); 

      List<string> zaman = new List<string>(); 

      List<string> deger = new List<string>(); 

      while (!reader.EndOfStream) 
      { 
       var satir = reader.ReadLine(); 
       var degerler = satir.Split(','); 
       if (degerler.Count() > 1) 
       { 
        zaman.Add(degerler[0]); 
        deger.Add(degerler[1]); 
       } 
      } 
      MessageBox.Show("Zaman ve değer listelere atıldı"); 
      chart1.Series["Series1"].XValueType = ChartValueType.Time; 
      chart1.ChartAreas["ChartArea1"].AxisX.LabelStyle.Format = "M-d-yyyy HH:mm:ss"; 
      DateTime newdatetime = new DateTime(); 
      for (int i = 0; i < zaman.Count; i++) 
      { 
       newdatetime = DateTime.ParseExact(zaman[i], "M-d-yyyy HH:mm:ss", CultureInfo.InvariantCulture); 
       chart1.Series["Series1"].Points.AddXY(newdatetime.ToString("M-d-yyyy HH:mm:ss")); 
      } 
      for (int j = 0; j < deger.Count; j++) 
      { 
       chart1.Series["Series1"].Points.AddY(deger[j]); 
      } 

     } 

     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message); 
     } 
    } 

任何幫助將非常appreciated.Thank你

+0

您能給我們從CSV線更放鬆一點? – bdimag 2014-09-24 14:57:04

+0

@bdimag肯定例如第一行是這樣的09/18/2014 23:15:08.170 \t 3.2573974589612531 – 2014-09-24 15:00:25

回答

0

你將要使用DateTime.ParseExact用有效的格式字符串:

 string toParse = "09/18/2014 23:15:08.170"; 
     DateTime d = DateTime.ParseExact(toParse, "MM/dd/yyyy HH:mm:ss.fff", System.Globalization.CultureInfo.InvariantCulture); 
+0

對不起,但我仍然有同樣的問題:/ – 2014-09-24 18:32:06

+0

什麼是使用ParseExact更新的代碼行,什麼是它失敗的輸入? – user1112560 2014-09-24 18:43:52

+0

我在看到斷點時看到的東西,沒有任何關於日期值的內容正在填充列表。 – 2014-09-24 18:46:33

0

DateTime.ParseExact的字符串解析必須完全匹配提供的格式...在你的情況下,你應該有。

"MM/dd/yyyy HH:mm:ss.fff" 

還有Parse和的TryParse,這將是

+0

不好意思,但問題仍然是一樣的 – 2014-09-24 18:34:13