2016-06-20 91 views
0

我正在創建一個時鐘進入企業。這裏是我的代碼:在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文件中寫入:時間戳,名稱,輸入。當我通過時鐘測試代碼時,程序正確寫入一行。當我進入時鐘後,它會創建兩行我同步,一行同步輸出。我想知道是否有人可以幫我找到代碼中出了什麼問題。謝謝。

回答

0

將文件寫入文件後需要清空csvData。

+0

當我添加csvData = null;在button10_Click結束時,程序崩潰時,程序崩潰。當我輸入時它工作正常。 – LUKER

+0

你遇到過什麼錯誤?最好清除它而不是將值設置爲空。 –

+0

csvData.Clear();而不是將其設置爲空。 –