CSV文件的多个数据类型值

时间:2014-05-30 15:14:25

标签: c# csv export-to-csv streamwriter

有人可以解释如何将具有不同值类型的多个值写入CSV文件。我知道你必须使用Stream编写器,但是如何在写入文件之前准备值?

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;
}

2 个答案:

答案 0 :(得分:0)

CSV文件是文本文件,因此所有String值都是如此。将ToString()放在您要写的每个值的末尾,然后将其写入。

一种可能的方法:

StringBuilder sb = new StringBuilder();
foreach (value you mean to write)
{
    sb.Append(thevalue.ToString());
}
//write the line to the stream as sb.ToString()

答案 1 :(得分:0)

目前还不清楚自己想做什么。 如果你想要一个包含所有值的行,那么我首先在​​你的职位类中编写ToCsv()方法 -

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

然后我制作一个数组并加入

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());