Search code examples
c#text-filesinstances

Creating and storing values of class objects from a text file


I am trying to find a way to creat class instances from a file and also to use that file as a way to give the class properties their values. I can manually put all the information in but it will be better to do it through a file so I can alter the file, which will alter the program for me.

Here is the code so far... When I run it, it says

class Program
{
    class dish
{
     public class starters { public string starter; public string alteration; }


    static void Main(string[] args)
    {
        List<dish.starters> starter = new List<dish.starters>();
        using (StreamReader reader = File.OpenText(@"D:\Visual Studio\Projects\Bella Italia\Food\Starters.txt"))
        {
            IDictionary<string, dish.starters> value = new Dictionary<string, dish.starters>();
            while (!reader.EndOfStream)
            {
                value[reader.ReadLine()] = new dish.starters();
                value[reader.ReadLine()].starter = reader.ReadLine();
            }
            foreach(var x in value.Values)
            {
                Console.WriteLine(x.starter);
            }

        }

        Console.ReadLine();

    }
}

}

When I try to run it, it says

Exception Unhandled System.Collections.Generic.KeyNotFoundException: 'The given key was not present in the dictionary.'


Solution

  • You are reading two consecutive line here. The second line probably doesn't have an associated entry in the dictionary (and you don't want that duplication either):

    value[reader.ReadLine() /*one*/] = new dish.starters();
    value[reader.ReadLine() /*two*/].starter = reader.ReadLine();
    

    Store the key in a variable and reuse that:

    string key = reader.ReadLine();
    
    value[key] = new dish.starters();
    value[key].starter = reader.ReadLine();
    

    Or create the object and assign later:

    string key = reader.ReadLine();
    
    var starters = new dish.starters();
    starters.starter = reader.ReadLine()
    
    value[key] = starters;