【问题标题】:Renaming files programmatically, decrementing以编程方式重命名文件,递减
【发布时间】:2015-07-13 00:42:30
【问题描述】:

我有一个文件夹,其中包含一定数量的名为 1.txt, 2.txt 3.txt 等的文本文件。

我的目标是,当其中一个被删除时,将任何大于已删除文件的文件重命名为一个。

例如。如果 1.txt 被删除,2 应该重命名为 1,3 重命名为 2,以此类推。

这是我目前的尝试:

 private void deletequestionbtn_Click(object sender, EventArgs e)
    {

        string fileDel = testfolderdialog.SelectedPath.ToString() + @"\" + questionCountint.ToString() + ".txt";
        DirectoryInfo d = new DirectoryInfo(testfolderdialog.SelectedPath.ToString() + @"\");

        File.Delete(fileDel);
        questionCountint++;

        foreach (var file in d.GetFiles("*.txt"))
        {
            string fn = file.Name;
            string use = fn.Replace(".txt", "");
            int count = int.Parse(use);

            if (count > questionCountint)
            {              
                File.Move(fileDel, testfolderdialog.SelectedPath.ToString() + @"\" + questionCountint--.ToString() + ".txt");
            }          
        }             
    }

问题出现在File.Move 行,它说它无法在fileDel 中找到文件,尽管我在删除fileDel 后递增questionCountint

我是不是以错误的方式处理这个问题?有没有更有效的方法来编写foreach 语句?我只想重命名大于删除文件的文件。

我哪里错了?

【问题讨论】:

  • XY 问题,“我怎样才能滚动我自己的原木滚筒来旋转我的原木”
  • 附言。答案是正则表达式。 xkcd.com/208
  • 你有没有看过我们用来构建目标文件名的`questionCountint的值是什么?我想你会发现它不是你期望的值。
  • @Alex 我刚刚检查过。删除 2.txt 后,questionCountint 变为 3。但在 File.Move 行中,它告诉我找不到 2.txt...不确定为什么要查找它,因为 questionCountint 为 3..

标签: c# file rename


【解决方案1】:

问题是您试图重命名fileDel,这是您已删除的文件。你应该重命名file

但是,您很快就会遇到下一个问题。如果您没有按照您期望的确切顺序获取文件,您将尝试将文件重命名为已存在的名称。

如果GetFiles方法按"3.txt", "2.txt"的顺序返回文件,你会先尝试将"3.txt"重命名为"2.txt",但"2.txt"已经存在。

您应该首先遍历文件并收集所有应该重命名的文件。然后,您应该按编号对文件进行排序,以便您可以按正确的顺序重命名它们。

由于文件名的格式很容易根据数字重新创建,因此您只需获取列表中的数字即可:

List<int> files = new List<int>();
foreach (var file in d.GetFiles("*.txt")) {
  string fn = file.Name;
  string use = fn.Replace(".txt", "");
  int count = int.Parse(use);
  if (count > questionCountint) {
    files.Add(count);
  }
}
string path = testfolderdialog.SelectedPath.ToString();
foreach (int count in files.Ordery(n => n)) {
  File.Move(String.Concat(path, count.ToString() + ".txt"), String.Concat(path, (count - 1).ToString() + ".txt");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-10
    • 2014-09-11
    • 2011-11-02
    • 2023-03-11
    • 2017-06-24
    相关资源
    最近更新 更多