【发布时间】: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..