Search code examples
c#csvtype-conversioncsvhelper

c# - Reading From CSV, Type Conversion Error


I'm using CSVHelper, though this seems to occur with the manual methods I know.

I'm trying to create some form of "save data" system using csv files, which will store all important variables that need to be loaded on the program running. Here's my code with generalized variable names:

        StringReader csv = new StringReader(SaveData);
        var load = new CsvReader(csv);
        string convertableString = "";
        load.Read();

        convertableString = load.GetField(0);
        day = Convert.ToInt32(convertableString);
        numberOfObjects = load.GetField<int>(1);

        for (int i = 0; i < numberOfObjects; i++)
        {
            load.Read();

            myObject[i].objName = load.GetField(0);
            myObject[i].objBool = load.GetField<bool>(1);
            myObject[i].objInt = load.GetField<int>(2);
        }

The lines that convert the strings to other variable types trigger the following error:

System.FormatException: 'Input string was not in a correct format.'

Specifically, the first line to throw this is:

day = Convert.ToInt32(convertableString);

This also applies to CSV Helper's conversion method however, this making the line (note that this requires deletion of the line above it):

day = load.GetField<int>(0);

For the sake of simplicity I'm showing both conversion methods and both return this (upon trying to convert anything, and yes "day" is an int)

My CSV file looks like this:

2,1,
Name, True, 45

I don't claim to have the best knowledge of coding but I'm getting there, though I can't really see what exactly is getting wrong, this isn't even my first time reading csv files and I've never experienced anything like this before.


Solution

  • I have since found the solution, firstly the csvReader was declared wrong, it should've been surrounded by this:

    using (TextReader fileReader = File.OpenText(saveData))
    {
        var load = new CsvReader(fileReader);
    
        \\\Rest of code here\\\
    
    }
    

    What the original code was doing was sending the filepath to the CsvReader rather than the actual file, this meant that the first field was set to the filepath, with no other data present. The original code tried to convert the filepath into an integer, which caused it to crash. This resolves the problem entirely.

    In this specific scenario (loading data on loading the program) it's also important to initialise your classes, so adding a line for that also prevents crashes.