2014-10-29 69 views
-1

我有一個CSV文件,我需要在C#中打開作爲一個順序文件。它必須由頭文件解析。解析CSV數據基於頭然後加載到數組

截至目前,我只知道如何將數據文件作爲使用C#System.IO庫的順序文件加載到ArrayList結構中。文件中的每一行都必須是單獨的記錄。這是它:

using System; 
using System.IO; 
using System.Collections; 

namespace FileSearch 
{ 
class Class1 
{ 
    static void Main(string[] args) 
    { 
     StreamReader objReader = new StreamReader("c:\\Users/Sarah/Desktop/IP4Data.csv"); //open file to read 
     string sLine = ""; //string variable for data that goes into ArrayList 
     ArrayList arrText = new ArrayList(); 

     while (sLine != null) 
     { 
      sLine = objReader.ReadLine(); //read file one line at a time 
      if (sLine != null) //if empty, it's null 
       arrText.Add(sLine);//Add data to Array List 
     } 
     objReader.Close(); //end loop 

     foreach (string sOutput in arrText) //Outputs read data from ArrayList onto screen 
      Console.WriteLine(sOutput); 
     Console.ReadLine(); 
    } 
} 
} 

如何解析CSV文件,以便它可以在ArrayList中搜索?

+0

分開你讀過如何CSV文件建立?如果是的話,你有理解嗎?如果是的話,你開始實施它嗎? – 2014-10-29 19:52:45

+1

你使用'ArrayList'而不是'List <>'的任何原因?不是它是無效的,[這只是做它的老方法](http://stackoverflow.com/a/2309699/1765721)。 – 2014-10-29 19:55:18

+1

你需要提供一個CSV樣本,並描述你的意思是「searchable」。 – Jonesopolis 2014-10-29 20:04:15

回答

1

你可以用String.Split方法分割每一行。 像

var fields = sLine.Split(new char[]{','}); 

如果你的價值觀是由逗號

+0

如果','會在字段值內部? – 2014-10-29 19:59:12

+0

我不知道如何在CSV文件的字段中使用分隔符的方式,如果可能的話,符號必須以某種方式逃脫我想。 – Michael 2014-10-29 20:02:06