c# – 如何在下一次打开csv文件的下一行写入?

前端之家收集整理的这篇文章主要介绍了c# – 如何在下一次打开csv文件的下一行写入?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在第一次运行时,我的程序写入第一行的csv文件,
但是,当我在第二个……第三个时间运行我的程序时,它会在第一行运行.
我怎么能纠正它?

我想输入所有进入我程序的CSV文件.

代码如下:

private void WriteToCsvFile()
{
    var us = users.ElementAt(0);
    string names = "Number',";
    string userAnswer = (us.userName + ",");
    foreach (string ss in user)
    {
        string str = Path.GetFileName(ss);
        names = names + str + ",";
    }
    foreach (string ans in us.answer)
    {
        userAnswer = userAnswer + ans + ",";
    }

    using (StreamWriter sw = new StreamWriter("EntranceLog.csv"))
    {
        sw.WriteLine(names);
        sw.WriteLine(userAnswer);

    }

    this.Close();
}

解决方法

在构造函数添加true参数:
using (StreamWriter sw = new StreamWriter("EntranceLog.csv",true))

名为append的第二个参数控制是否覆盖或附加现有文件. MSDN州:

true to append data to the file; false to overwrite the file. If the specified file does not exist,this parameter has no effect,and the constructor creates a new file.

猜你在找的C#相关文章