Reading CSV file and storing values into an array

后端 未结 19 1783
猫巷女王i
猫巷女王i 2020-11-22 06:35

I am trying to read a *.csv-file.

The *.csv-file consist of two columns separated by semicolon (\";\").

I am able

19条回答
  •  深忆病人
    2020-11-22 07:08

    Here's a special case where one of data field has semicolon (";") as part of it's data in that case most of answers above will fail.

    Solution it that case will be

    string[] csvRows = System.IO.File.ReadAllLines(FullyQaulifiedFileName);
    string[] fields = null;
    List lstFields;
    string field;
    bool quoteStarted = false;
    foreach (string csvRow in csvRows)
    {
        lstFields = new List();
        field = "";
        for (int i = 0; i < csvRow.Length; i++)
        {
            string tmp = csvRow.ElementAt(i).ToString();
            if(String.Compare(tmp,"\"")==0)
            {
                quoteStarted = !quoteStarted;
            }
            if (String.Compare(tmp, ";") == 0 && !quoteStarted)
            {
                lstFields.Add(field);
                field = "";
            }
            else if (String.Compare(tmp, "\"") != 0)
            {
                field += tmp;
            }
        }
        if(!string.IsNullOrEmpty(field))
        {
            lstFields.Add(field);
            field = "";
        }
    // This will hold values for each column for current row under processing
        fields = lstFields.ToArray(); 
    }
    

提交回复
热议问题