Reading CSV file and storing values into an array

后端 未结 19 1874
猫巷女王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:05

    Still wrong. You need to compensate for "" in quotes. Here is my solution Microsoft style csv.

                   /// 
        /// Microsoft style csv file.  " is the quote character, "" is an escaped quote.
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public static List ReadCSVFileMSStyle(string fileName, char sepChar = ',', char quoteChar = '"')
        {
            List ret = new List();
    
            string[] csvRows = System.IO.File.ReadAllLines(fileName);
    
            foreach (string csvRow in csvRows)
            {
                bool inQuotes = false;
                List fields = new List();
                string field = "";
                for (int i = 0; i < csvRow.Length; i++)
                {
                    if (inQuotes)
                    {
                        // Is it a "" inside quoted area? (escaped litteral quote)
                        if(i < csvRow.Length - 1 && csvRow[i] == quoteChar && csvRow[i+1] == quoteChar)
                        {
                            i++;
                            field += quoteChar;
                        }
                        else if(csvRow[i] == quoteChar)
                        {
                            inQuotes = false;
                        }
                        else
                        {
                            field += csvRow[i];
                        }
                    }
                    else // Not in quoted region
                    {
                         if (csvRow[i] == quoteChar)
                        {
                            inQuotes = true;
                        }
                        if (csvRow[i] == sepChar)
                        {
                            fields.Add(field);
                            field = "";
                        }
                        else 
                        {
                            field += csvRow[i];
                        }
                    }
                }
                if (!string.IsNullOrEmpty(field))
                {
                    fields.Add(field);
                    field = "";
                }
                ret.Add(fields.ToArray());
            }
    
            return ret;
        }
    }
    

提交回复
热议问题