2011-10-07 62 views
1

我有這部分代碼需要一個文件,並將其放入ArrayList。將輸入的文件將是CSV(我使用的當前CSV在第一行有標題,所以我不需要該行),第二行必須放入ArrayList不能分割線

我使用ArrayList,因爲該文件可以是動態的,所以我不確定第二行的長度是多少。我測試過(在第二行有7個以逗號分隔的文件)此代碼,它打印出ArrayList的長度爲(fileList.Count)= 1。

出現了什麼問題?

ArrayList fileList2 = new ArrayList(); 
private void button3_Click(object sender, EventArgs e) 
{ 
    string filename = ""; 
    DialogResult result = openFileDialog2.ShowDialog(); 
    if (result == DialogResult.OK) 
    { 
     filename = openFileDialog2.FileName; 
     textBox3.Text = filename; 
     string line2; 
     System.IO.StreamReader file2 = new System.IO.StreamReader(textBox3.Text); //reads file from textbox 
     stringforData = file2.ReadLine();  // this reads the first line that I dont need 
     while ((line2 = file2.ReadLine()) != null)  //read the lines 
     { 
      // puts elements into array 
      fileList2.Add(line2.Split(';'));//split the line and put it in the arraylist 
     } 
     file2.Close(); 
     if (true) // this is for testind what is happening 
     { 
      this.textBox2.Clear(); 
      textBox3.Text = Convert.ToString(fileList2.Count); 
     } 
    } 
} 
+4

2011年爲什麼要使用ArrayList?它已被棄用多年,現在,如果Baszz是正確的,你的例子顯示了爲什麼 – Dyppl

+0

要增加什麼Dyppl說,看到[這個問題](http://stackoverflow.com/questions/5063156/why-isnt-arraylist-marked -obsolete)。 – R0MANARMY

+0

@Dyppl我應該使用什麼和如何? –

回答

5

難道你不想使用fileList2.AddRange()而不是fileList2.Add()? 在我看來,你現在正在向fileList添加一個項目。該項目是一個數組,其中包含您實際想要添加到列表中的所有項目。如果你首先得到這個數組並且使用addRange方法,那應該沒問題。

+0

+1對我來說看起來也是錯誤..無論如何,我認爲這個問題是不正確的,因爲filelist2從來沒有在這個內部定義,並且OP在告訴我們文件列表計數是1 ... – gbianchi

+1

也是:他談論一個逗號分隔線,而他正在分裂; – mtijn

+0

@mtijn:這很可能是好的,CSV文件通常在某些語言環境中(如俄語)帶有分號分隔符,但它們仍稱爲CSV – Dyppl

0

首先,您應該使用AddRange(),而不是Add()。其次,如果這是一個CSV文件,那麼爲什麼要將分號傳遞給split()方法?

+0

我正在使用csv's;'not',' –

+0

請指定此項,CSV意味着逗號。 – MGZero