在C#中写入CSV文件

时间:2016-06-20 03:32:12

标签: c# csv

我正在创建一个用于计时业务的时钟。这是我的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
    String Code;
    String Name;
    String InOut;
    Boolean Luke = true;
    String csvPath = "C:/users/luke/documents/C#/csvProject.csv";
    StringBuilder Header = new StringBuilder();
    StringBuilder csvData = new StringBuilder();



    public Form1()
    {
        InitializeComponent();
        FormBorderStyle = FormBorderStyle.None;
        WindowState = FormWindowState.Maximized;
        TopMost = true;

        Header.AppendLine("Timestamp, Name");
        File.AppendAllText(csvPath, Header.ToString());
        textBox1.Font = new Font("Arial", 30, FontStyle.Bold);


    }

    private void button_Click(object sender, EventArgs e)
    {
        Button button = (Button)sender;
        Code = Code + button.Text;
        textBox1.Text = Code;
    }

    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Escape)
        {
            FormBorderStyle = FormBorderStyle.Sizable;
            WindowState = FormWindowState.Normal;
            TopMost = false;
        }
    }

    private void button13_Click(object sender, EventArgs e)
    {
        //clear
        Code = null;
        textBox1.Text = Code;
    }

    private void button10_Click(object sender, EventArgs e)
    {
        //in or out
        DateTime timeStamp = DateTime.Now;
        if (Code == "123")
        {
            Name = "Luke";
        }
        Button button = (Button)sender;
        csvData.AppendLine(timeStamp + "," + Name + "," + button.Text);
        File.AppendAllText(csvPath, csvData.ToString());
        Code = null;
        textBox1.Text = Code;
    }

    private void button14_Click(object sender, EventArgs e)
    {

    }
}
}

我的布局包括数字键盘,按钮和按钮。当用户在输入代码后按下输入按钮时,程序应写入CSV文件:时间戳,名称,输入。当我通过计时测试代码时,程序正确地写入一行。当我进入时钟然后输出时,它会创建两行我的时钟输入和一行我的时钟输出。我想知道是否有人可以帮我找到代码中出错的地方。感谢。

1 个答案:

答案 0 :(得分:0)

将csvData写入文件后需要清空。