2016-11-21 66 views
0

随着社区的一些以前的反馈,我已经实现了一个函数,用于检查文件是否存在,如果不存在,那么它会写入头文件和数据,但如果它存在它只能附加到它。那么这就是它应该做的,但它所做的只是写入没有标题的数据。就好像它跳出第一个条件,然后进入下一个条件。我哪里错了?将头添加到不存在的文件然后追加

private void button6_Click_2(object sender, EventArgs e) 
    { 

     int count_row = dataGridView1.RowCount; 
     int count_cell = dataGridView1.Rows[0].Cells.Count; 
     string path = "C:\\Users\\jdavis\\Desktop\\" + comboBox5.Text + ".csv"; 
     string rxHeader = "Code" + "," + "Description" + "," + "NDC" + "," + "Supplier Code" 
     + "," + "Supplier Description" + "," + "Pack Size" + "," + "UOM"; 


     MessageBox.Show("Please wait while " + comboBox5.Text + " table is being exported.."); 

     for (int row_index = 0; row_index <= count_row - 2; row_index++) 
     { 

      for (int cell_index = 1; cell_index <= count_cell - 1; cell_index++) 
      { 
       textBox8.Text = textBox8.Text + dataGridView1.Rows[row_index].Cells[cell_index].Value.ToString() + ","; 

      } 
      textBox8.Text = textBox8.Text + "\r\n"; 

      if (!File.Exists(path)) 
      { 
       System.IO.File.WriteAllText(path, rxHeader); 
       System.IO.File.WriteAllText(path, textBox8.Text); 
      } 
      else 
      {  
       System.IO.File.AppendAllText(path, textBox8.Text); 
       MessageBox.Show("Export of " + comboBox5.Text + " table is complete!"); 
       textBox8.Clear(); 
      } 
     } 
    } 
+2

很确定您希望第二次调用是'Append',而不是'Write'。更改为:'System.IO.File.WriteAllText(path,rxHeader);''System.IO.File.AppendAllText(path,textBox8.Text);'。没有这个改变,第二次调用基本上删除文件,然后只写入'textBox8.Text'。 – Quantic

+0

@Quantic这在一定程度上工作,但问题是,标题和第一个记录添加好,但当我关闭该程序并追加一个新的记录。它复制现有记录,然后添加我添加的新记录。 (我的数据存储在我的数据库中,我将其保存并通过我的c#应用程序展示给CSV文件)我不确定这是否很重要 – Jevon

回答

1

的问题是,File.WriteAllText覆盖文件的内容,那么你的第二File.WriteAllText覆盖头。您可以更改您的代码,如下所示:

 if (!File.Exists(path)) 
     { 
      System.IO.File.WriteAllText(path, rxHeader + textBox8.Text); 
     } 
     else 
     {  
      System.IO.File.AppendAllText(path, textBox8.Text); 
      MessageBox.Show("Export of " + comboBox5.Text + " table is complete!"); 
      textBox8.Clear(); 
     } 
+0

好的,这在一定程度上有效。首先,程序将头单独写入文件。我必须再次写入文件才能添加数据。但是这里是一个奇怪的部分,数据首先写入文件作为重复,然后添加第三个数据。所以基本上两个相同的条目,然后一个条目 – Jevon

+0

找出问题。谢谢。 – Jevon

相关问题