2016-11-21 16 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

2番目の呼び出しを 'Write'ではなく' Append'にしますか?これに変更: 'System.IO.File.WriteAllText(path、rxHeader);' 'System.IO.File.AppendAllText(path、textBox8.Text);'。この変更がなければ、2番目の呼び出しは基本的にファイルを削除し、 'textBox8.Text'だけを書き込みます。 – Quantic

+0

@Quanticこれはある程度までは機能しますが、ヘッダーと最初のレコードはOKですが、プログラムを閉じて新しいレコードを追加すると問題になります。既存のレコードを複製し、追加した新しいレコードを追加します。 (私のデータは私のデータベースに保存され、CSVファイルに保存されます。私のデータベースに保存され、CSVファイルにはC#アプリケーションで書き出されます)。問題がある場合は、 – 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

okです。最初に、プログラムはヘッダーだけをファイルに書き込みます。私はファイルに2回目のデータを追加する必要があります。しかし、ここでは奇妙な部分があります。最初にデータが重複としてファイルに書き込まれ、次に第3のデータが追加されます。だから基本的に2つの同じエントリと1つのエントリ – Jevon

+0

問題を見つけました。ありがとうございました。 – Jevon

関連する問題