Ejemplo n.º 1
0
        /// <summary>
        /// Load a CSV file, read all entries and return ListItem objects
        /// </summary>
        /// <param name="filename">CSV file</param>
        /// <returns>Enumarator of ListItem objects</returns>
        public static IEnumerable<ListItem> LoadCSV(string filename)
        {
            char valuedelimiter = ',';
            char keywordDelimiter = ';';
            string[] lineParts;
            List<ListItem> listItems = new List<ListItem>();
            List<string> headers = new List<string>() ;
            int lineCounter = 0;

            try
            {
                using (var textReader = new System.IO.StreamReader(filename))
                {
                    while (!textReader.EndOfStream)
                    {
                        lineCounter++;
                        lineParts = textReader.ReadLine().Split(valuedelimiter);

                        // The first line should be a header, read that to know the index of the columns
                        if (lineCounter==1)
                        {
                            for (int h = 0; h < lineParts.Length; h++)
                                headers.Add(lineParts[h]);
                            continue;
                        }

                        // Do some validation on this line
                        if (lineParts.Length != headers.Count())
                            throw new FormatException("Number of values doesn't match number of headers.");

                        ListItem newListItem = new ListItem();
                        // Get the all the values, whatever they are
                        for (int i=0;i<lineParts.Length;i++)
                        {
                            // Keywords need special handling
                            if (headers[i]=="keywords")
                            {
                                string[] keywords = lineParts[i].Split(keywordDelimiter);
                                foreach (string keyword in keywords)
                                    newListItem.AddKeyword(keyword);
                            }
                            else if (isString(lineParts[i]))
                                newListItem[headers[i]] = lineParts[i];
                            else
                                newListItem[headers[i]] = int.Parse(lineParts[i]);

                        }

                        listItems.Add(newListItem);
                    }
                    return listItems;
                }
            }
            catch (FormatException ex)
            {
                throw new FormatException("Error parsing CSV file " + filename + " at line " + lineCounter, ex);
            }
        }