0

Could someone explain how to write multiple values with different value types to a CSV file. I gather you have to use a Stream writer, but how do i prepare the values before writing to the file?

public static void SaveGame(GridReference[] TrapPositions, GridReference MonsterPosition, GridReference PlayerPosition, GridReference FlaskPosition, bool MonsterAwake)
{
    //StreamWriter sw = new StreamWriter (filename);

    /* string filePath = "path" + "filename.csv";
    if (!File.Exists(filePath))
    {
        File.Create(filePath).Close();
    } */

    string delimiter = ",";

    int PlayerX = PlayerPosition.X_CoOrd;
    int PlayerY = PlayerPosition.Y_CoOrd;
    bool Awake = MonsterAwake;
    int FirstTrapX = TrapPositions [1].X_CoOrd;
    int FirsttrapY = TrapPositions [1].Y_CoOrd;
    int SecondTrapX = TrapPositions [2].X_CoOrd;
    int SecondTrapY = TrapPositions [2].Y_CoOrd;
    int MonsterX = MonsterPosition.X_CoOrd;
    int MonsterY = MonsterPosition.Y_CoOrd;
    int FlaskX = FlaskPosition.X_CoOrd;
    int FlaskY = FlaskPosition.Y_CoOrd;
}
Graham Warrender
  • 365
  • 1
  • 8
  • 20

2 Answers2

0

A CSV file is a text file, so all String values. Put ToString() on the end of every value you mean to write and then write it.

One possible approach:

StringBuilder sb = new StringBuilder();
foreach (value you mean to write)
{
    sb.Append(thevalue.ToString());
}
//write the line to the stream as sb.ToString()
DonBoitnott
  • 10,787
  • 6
  • 49
  • 68
0

It isn't exactly clear what you want to do. If you want a single row with all your values then I'd start by writing a ToCsv() method in your position class-

internal public ToCsv()
{
   return X_CoOrd + "," + Y_CoOrd;
}

Then I'd make an array and join it

var vals = new List<string>();
vals.Add(PlayerPosition.ToCsv());
foreach (var trapPosition in TrapPositions)
    vals.Add(trapPosition.ToCsv());
vals.Add(MonsterPosition.ToCsv());
vals.Add(FlaskPosition.ToCsv());
vals.Add(MonsterAwake.ToString());
File.WriteAllText("filename.csv", string.Join(",", vals.ToArray());
bookemdano
  • 121
  • 1
  • 5
  • Aim is to save the values held in the variables to a CSV file so that they can used, to effectively load the game at a later stage. – Graham Warrender May 30 '14 at 15:48