我不知道为什么代码无法正常工作,当我单击保存按钮向我显示Yokoso Log(1)时,第二次保存显示了Yokoso Log(1).txt(2).txt .....

            //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).");
        }

    }

最佳答案

您尝试做的是这样的:

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

File.Create(currentPath);
...

10-07 19:54