2016-06-08 35 views
1

我不明白爲什麼代碼不能正常工作,當我點擊保存按鈕顯示我橫月日誌(1)然後第二個保存顯示橫山日誌(1).txt(2 ).TXT .....保存.text文件增量

  //Create txt and write 

     string logPath = Path.Combine(
     Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Yokoso Log\\Yokoso Log"); 
     TextWriter txtwrite = new StreamWriter(logPath); 

     int count = 1; 

     Find: 
     if (File.Exists(logPath)) 
     { 
      logPath = logPath + "(" + count.ToString() + ").txt"; 
      count++; 
      goto Find; 
     } 
     else 
     { 
      File.Create(logPath); 

      for (int i = 0; i < dataGridView1.Rows.Count - 1; i++) 
      { 
       for (int j = 0; j < dataGridView1.Columns.Count; j++) 
       { 
        txtwrite.Write("\t" + dataGridView1.Rows[i].Cells[j].Value.ToString() + "\t" + "|"); 
       } 
       txtwrite.WriteLine(""); 
       txtwrite.WriteLine("____________________________________________________________________"); 

      } 
      txtwrite.Close(); 
      MessageBox.Show("Log create successfully (directory desktop)."); 
     } 

    } 
+1

...因爲你是在一個循環中加入'logPath'。 – stuartd

回答

3

你正在嘗試做的是這樣的:

var currentPath = logPath; 
while (File.Exists(currentPath)) 
{ 
    currentPath = logPath + "(" + count.ToString() + ").txt"; 
    count++; 
} 

File.Create(currentPath); 
... 
+0

謝謝,我明白了。 –

0

這裏要創建一個文件

TextWriter txtwrite = new StreamWriter(logPath); 

那麼當您在檢查該文件果然有一個文件

if (File.Exists(logPath)) 

這就是我想你的意思做

string logPath = Path.Combine(
    Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Yokoso Log\\Yokoso Log"); 

    int count = 1; 
    while (File.Exists(logPath)) 
    { 
     logPath = logPath + "(" + count.ToString() + ").txt"; 
     count++; 
    } 

    using (TextWriter txtwrite = new StreamWriter(logPath)) 
    { 
     for (int i = 0; i < dataGridView1.Rows.Count - 1; i++) 
     { 
      for (int j = 0; j < dataGridView1.Columns.Count; j++) 
      { 
       txtwrite.Write("\t" + dataGridView1.Rows[i].Cells[j].Value.ToString() + "\t" + "|"); 
      } 
      txtwrite.WriteLine(""); 
      txtwrite.WriteLine("____________________________________________________________________"); 
     } 
    } 
    MessageBox.Show("Log create successfully (directory desktop).");