C# CSV Reader (compatible with unity)

Why?

I need a CSV (comma-separated values) parser to use in my next project, in Unity (C#). I looked at existing parsers but all the ones I found were missing some features, or not available in source code.
I ported the simple but efficient parser I made in my mobile games to C# (was C++).

It’s available on Github here.

Features

  • commas inside cells
  • quotes inside cells
  • line breaks inside cells
  • empty cells
  • utf8 characters

I need all those features because I use csv mostly for localization. My latest game was ported to 11 languages (inclusing Chinese, Japanese and Russian) and I plan to support even more languages in the next one. I export the texts from a Google Doc sheet to csv.

How to use with Unity

Just use a TextAsset (csv files are recognized as text in Unity).

void MyReader(int line_index, List line)
{
// Will be called for each line parsed from the csv
...
}

TextAsset text_asset = Resources.Load("csv_file");
fgCSVReader.Load(text_asset.text, new fgCSVReader.ReadLineDelegate(MyReader));

Improvements

It can be useful to stream the data when reading huge files. I don’t need it and it’s easier with Unity to read the whole file at once so I didn’t implement it.

License

Feel free to use/improve/share/update the code as you wish.
Send me a tweet @Frozax if you like it.

Comments

  1. Avatar Dimitri Landais

    Hi :)
    I think I found a small bug in your code. I’m using it to parse localized text strings exported from Google Sheets too. The last line of one of my csv file wasn’t read at all. It turns out, when the last line of a file doesn’t end with a \n or “, the default behaviour of the switch is used, but it doesn’t call the line_reader callback for the last line.

    Adding this code in the default clause fixes it:
    //end of file without a trailing \n or ”
    if(cur_file_index == file_length)
    {
    cur_line.Add(cur_item.ToString());
    line_reader(cur_line_number++, cur_line);
    }

    It works properly for me with that fix :) thanks for the parser, keep up the good work!

    1. Avatar Wabolas

      Thanks for this fix Dimitri, and thanks for the original parser, frozax :)

  2. Avatar frozax

    Thanks Dimitri for the comment. I’m glad this code was useful to you :)

Comments are closed.