保存.text文件增量

时间:2016-06-08 15:33:33

标签: c# visual-studio

我无法弄清楚为什么代码无法正常工作,当我点击保存按钮显示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).");
        }

    }

2 个答案:

答案 0 :(得分:3)

你要做的是这样的事情:

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

File.Create(currentPath);
...

答案 1 :(得分:0)

这里你要创建一个文件

Contentpane

然后当你检查文件时确定有一个文件

TextWriter txtwrite = new StreamWriter(logPath);

这就是我认为你的意思

if (File.Exists(logPath))