Reading CSV file and storing values into an array

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

    Hi all, I created a static class for doing this. + column check + quota sign removal

    public static class CSV
    {
        public static List Import(string file, char csvDelimiter, bool ignoreHeadline, bool removeQuoteSign)
        {
            return ReadCSVFile(file, csvDelimiter, ignoreHeadline, removeQuoteSign);
        }
    
        private static List ReadCSVFile(string filename, char csvDelimiter, bool ignoreHeadline, bool removeQuoteSign)
        {
            string[] result = new string[0];
            List lst = new List();
    
            string line;
            int currentLineNumner = 0;
            int columnCount = 0;
    
            // Read the file and display it line by line.  
            using (System.IO.StreamReader file = new System.IO.StreamReader(filename))
            {
                while ((line = file.ReadLine()) != null)
                {
                    currentLineNumner++;
                    string[] strAr = line.Split(csvDelimiter);
                    // save column count of dirst line
                    if (currentLineNumner == 1)
                    {
                        columnCount = strAr.Count();
                    }
                    else
                    {
                        //Check column count of every other lines
                        if (strAr.Count() != columnCount)
                        {
                            throw new Exception(string.Format("CSV Import Exception: Wrong column count in line {0}", currentLineNumner));
                        }
                    }
    
                    if (removeQuoteSign) strAr = RemoveQouteSign(strAr);
    
                    if (ignoreHeadline)
                    {
                        if(currentLineNumner !=1) lst.Add(strAr);
                    }
                    else
                    {
                        lst.Add(strAr);
                    }
                }
    
            }
    
            return lst;
        }
        private static string[] RemoveQouteSign(string[] ar)
        {
            for (int i = 0;i< ar.Count() ; i++)
            {
                if (ar[i].StartsWith("\"") || ar[i].StartsWith("'")) ar[i] = ar[i].Substring(1);
                if (ar[i].EndsWith("\"") || ar[i].EndsWith("'")) ar[i] = ar[i].Substring(0,ar[i].Length-1);
    
            }
            return ar;
        }
    
    }
    

提交回复
热议问题