2011-10-14 126 views
0

的专栏中,我有一个CSV文件是这样的:比较csv文件与表格

george, 
nick, 
mary, 
john, 
micheal 

用户可以使他喜欢的文件。所以他可以有4或5或28行。

我有一个其他的csv文件,我将它分配给名为fileList1的ArrayList。这个文件是一个议程。

如果议程中的名称不在csv中,则会给出该名称,然后打印消息。(这是我需要找到的)。问题是,两个csv都可以是动态的。行数不是标准的。

我也有一张表,colB[]。此表格包含将与列进行比较的文件列表。

问题是我无法选择arraylist中的特定列,因为它是一个数组列表。

ArrayList fileList1 = new ArrayList(); 
    string stringforData; 

    private void button1_Click(object sender, EventArgs e) 
      { 
       // opens **BROWSE** 

       string filename = ""; 
       DialogResult result = openFileDialog1.ShowDialog(); 
       if (result == DialogResult.OK) 
       { 
        filename = openFileDialog1.FileName; 

        textBox1.Text = filename; 

    // Read the file and display it line by line. 

        string line; 

        System.IO.StreamReader file1 = new System.IO.StreamReader(textBox1.Text); //reads the path from textbox 

        stringforData = file1.ReadLine();  
        while ((line = file1.ReadLine()) != null) 
        { 
         // bazei stoixeia mesa ston pinaka 
         fileList1.Add(line.Split(';'));//split the file and assign it in //the fileList1 
        } 
        file1.Close(); 
       } 
      } 


private void button3_Click(object sender, EventArgs e) 
      { 

       this.textBox2.Clear(); 
       string[] colB = new string[]; 

       for (int j = 0; j < colB.Length; j++) 
       { 
         if (Path.GetExtension(colB[j]) == ".csv") 
             { 

       string path = Path.GetDirectoryName(textBox1.Text); 
       string g = Path.Combine(path, colB[j]); 


       textBox2.Text += "the path is " + g + " " + Environment.NewLine; 


       System.IO.StreamReader gi = new System.IO.StreamReader(g); 
       string itemss; 
       ArrayList ArrayForLists=new ArrayList(); 
        while ((itemss = gi.ReadLine()) != null) 
             { 
       ArrayForLists.AddRange(itemss.Split(';'));// assign to the arraylist the list that we are searching 
       } 
       } 

回答

0

看来,一个ArrayList是不是一个好的选择,因为你不能选择所需的列。为什么不使用免费的C#CSV解析器: http://www.filehelpers.com/

从这里找到: CSV parser/reader for C#?

在上面的链接有还加载一个CSV到一个DataTable,它给你引用一个列中的选项的例子(而不是ArrayList)。


编辑: 我从给定的链接粘贴代码:

static DataTable CsvToDataTable(string strFileName) 
    { 
     DataTable dataTable = new DataTable("DataTable Name"); 

     using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0; Data Source = " + Directory.GetCurrentDirectory() + "; Extended Properties = \"Text;HDR=YES;FMT=Delimited\"")) 
     { 
      conn.Open(); 
      string strQuery = "SELECT * FROM [" + strFileName + "]"; 
      OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter(strQuery, conn); 

      adapter.Fill(dataTable); 
     } 
     return dataTable; 
    } 
+0

对不起汤姆,这是不想要的anwser。 –

+0

我编辑了我的答案。将CSV解析为DataTable不能解决您的问题吗?如果不是,你能解释为什么吗? – Tom

+0

如果我在我的项目中添加此代码,则出现错误。看人,我只需要一些代码或想法,以及如何将Arraylist切换到其他数据结构。 –