Search code examples
c#export-to-csv

What is wrong with my writing data to a csv file in c#?


I am attempting to write highscores from the game i am building in Unity to a CSV file. So far i have gotten this far:

    {
        string filepath = Application.dataPath;
        string newFileName = (Application.dataPath + "highscore.csv");
        StreamWriter writer = new StreamWriter(newFileName);
        writer.WriteLine("Score,Time");
        for (int i = 0; i < 5; i++)
        {
            writer.WriteLine(scoresAndSeconds[i, 0].ToString() + "," + scoresAndSeconds[i, 1].ToString());
        } 
    }

I am succeeding in creating the CSV file when I call the function, but nothing at all is being written. No errors are being thrown from the code.


Solution

  • You just need to flush the stream. To achieve that, just use the using statement

    using StreamWriter writer = new StreamWriter(newFileName);
    writer.WriteLine("Score,Time");
    for (int i = 0; i < 5; i++)
    {
        writer.WriteLine(scoresAndSeconds[i, 0].ToString() + "," + scoresAndSeconds[i, 1].ToString());
    } 
    

    Note you might want to look at a Csv library for more extensive CSV support