c# - 保存 .text 文件增量

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

    }

最佳答案

你想要做的是这样的:

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

File.Create(currentPath);
...

关于c# - 保存 .text 文件增量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37706935/

相关文章:

c# - 在 Visual Studio 中格式化文档以插入大括号?

git - 如何在具有多个协作者的环境中使用本地化的 PostBuildEvent?

c# - 注册抛出 'Inheritance security rules violated while overriding member'

c# - 为什么我无法调用 DbContextOptionsBuilder 上的 UseInMemoryDatabase 方法?

c# - 当前在 asp.net 日历控件中选择的月份

javascript - 逗号插入无限小数中

sql-server - SQL Server 错误预期 1 个导出,契约(Contract)名称为 Microsoft.VisualStudio.Utilities.IContentTypeRegistryService

c# - 从现有集合中初始化对象初始化程序中的只读集合

visual-studio - 与 Azure DevOps 符号服务器的源链接

vb.net - Visual Studio 2005 for VB 中的重构功能