C# Exception Handling continue on error

c#, csv, exception

Solution

if (myHashtable.ContainsKey(key))
    duplicates.Add(key);
else
    myHashtable.Add(key, value);

Problem

I have a basic C# console application that reads a text file (CSV format) line by line and puts the data into a HashTable. The first CSV item in the line is the key (id num) and the rest of the line is the value. However I've discovered that my import file has a few duplicate keys that it shouldn't have. When I try to import the file the application errors out because you can't have duplicate keys in a HashTable. I want my program to be able to handle this error though. When I run into a duplicate key I would like to put that key into a arraylist and continue importing the rest of the data into the hashtable. How can I do this in C# Here is my code: private static Hashtable importFile(Hashtable myHashtable, String myFileName) { ``` StreamReader sr = new StreamReader(myFileName); CSVReader csvReader = new CSVReader(); ArrayList tempArray = new ArrayList(); int count = 0; while (!sr.EndOfStream) { String temp = sr.ReadLine(); if (temp.StartsWith(" ")) { ServMissing.Add(temp); } else { tempArray = csvReader.CSVParser(temp); Boolean first = true; String key = ""; String value = ""; foreach (String x in tempArray) { if (first) { key = x; first = false; } else { value += x + ","; } } myHashtable.Add(key, value); } count++; } Console.WriteLine("Import Count: " + count); return myHashtable; } ```

Original source