Bissap
Bissap

Reputation: 551

An item with the same key has already been added C#

I'm trying to browse all *.txt files from folder to get metadata inside.

void SearchAndPopulate(string path, string searchText)
        {

            DirectoryInfo di = new DirectoryInfo(path);
            FileInfo[] files = di.GetFiles("*.txt");
            Dictionary<String, dynamic> dictionary = new Dictionary<String, Object>();
            int i = 0;
            foreach (FileInfo file in files)
            {
                dictionary.Add(String.Format("name{0}", i.ToString()), i);
                using (StreamReader sr = new StreamReader(file.FullName))
                {
                    string content = sr.ReadToEnd().ToLower();
                    if (content.Contains(searchText.ToLower()))
                    {
                               dictionary["name"+i] = File
                            .ReadAllLines(file.FullName)
                            .Select(y => y.Split('='))
                            .Where(y => y.Length > 1)
                            .ToDictionary(y => y[0].Trim(), y => y[1]);
                        var temp = dictionary["name" + i];
                        listBox1.Text = temp["NUM_CLIENT"];

                    }
                }
                i++;
            }


        }

I get "An item with the same key has already been added" for dictionary variable.

Upvotes: 1

Views: 7279

Answers (2)

juharr
juharr

Reputation: 32296

Honestly I don't think you need any dictionaries in your code. Also you can reduce the number of times you read in each file.

void SearchAndPopulate(string path, string searchText)
{
    DirectoryInfo di = new DirectoryInfo(path);
    FileInfo[] files = di.GetFiles("*.txt");
    foreach (FileInfo file in files)
    {
        var content = File.ReadAllLines(file.FullName);
        if (content.Any(line => line.ToLower().Contains(searchText.ToLower())))
        {
            var numClient = content.Select(y => y.Split('='))
                .Where(y => y.Length > 1 && y[0].Trim() == "NUM_CLIENT")
                .Select(y => y[1])
                .FirstOrDefault();
            if(numClient != null)
                listBox1.Text = numClient;
            else
                // Do something here if "NUM_CLIENT" wasn't in the file.
        }
    }
}

Upvotes: 0

Igor
Igor

Reputation: 62318

This exception is thrown when you try to add a duplicate entry in a Dictionary using the same key. The key value in a Dictionary must be unique.

Possible causes

  1. Look at the content of your file, you will find at least 2 lines where the left side of the = sign have the same string value.
  2. You have multiple empty values on the left side of the = sign in your file. You can correct this in your Linq statement by ignoring those lines:

    dictionary["name"+i] = File.ReadAllLines(file.FullName)
        .Select(y => y.Split('='))
        .Where(y => y.Length > 1 && !string.IsNullOrWhiteSpace(y[0]))
        .ToDictionary(y => y[0].Trim(), y => y[1]);
    

Upvotes: 4

Related Questions