Hi, I'm trying and failing to get this CSV reading library to work. I started making a question on accessing the data in CsvReader, which I could see in the debugger but couldn't work out how to access via code. However, I'm getting annother problem now which I wasn't before, even though the code is identical as far as I can tell!

The exception is:

System.Argument Exception: "An item with the same key has already been added."

The code is only a couple of lines, using the "LumenWorks" CSV library. The exception can just be ignored by pressing continue in the debugger...

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            // open the file "data.csv" which is a CSV file with headers
            using (CsvReader csv2 =
                   new CsvReader(new StreamReader("D:\\JFEE\\Grid Management Files\\2012-08-25_00-00-00.csv"), true))
            {
                int fieldCount = csv2.FieldCount; // <--- Exception occours here! 
                string[] headers = csv2.GetFieldHeaders();

                while (csv2.ReadNextRecord())
                {
                    for (int i = 0; i < fieldCount; i++)
                        Console.Write(string.Format("{0} = {1};",
                                      headers[i], csv2[i]));

                    Console.WriteLine();
                }
            }
        }
    }

Recommended Answers

All 2 Replies

I'd ask the author of the CVSReader, since the error is occuring in their code.

As a guess, I'd say it's creating column headers when you access FieldCount and their are duplicate column names.

Thanks, you are correct its because of multiple header names - I found a reference to it in the library discusion (but only as an "exception" so my frantic google searching didn't help!)

I actually deal with this in my full code so I figure the best thing I can do is catch the exception. I haven't noticed any ill affects.

Cheers!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.