【问题标题】:Why I can't rename my files and folders?为什么我不能重命名我的文件和文件夹?
【发布时间】:2016-07-24 09:43:44
【问题描述】:

所以我正在重新编写一个例程来重命名东西。我的文件夹树结构类似于:

Folder  ->  Folder(s)   -> Folder(s) + ImageFile(s)

Session ->  Location(s) -> Test(s)   + Images

所有位置都有相同的测试,重命名一个必须重命名所有。此外,每个图像都有一个相关文件夹与该图像同名。因此图像“一”、“二”、“三”将在同一目录(位置)中同时包含“一”、“二”、“三”文件夹。

我正在使用此代码重命名:

DirectoryInfo MainSessionFolder = new DirectoryInfo(FileStructure.CurrentSessionPath); // Main Session Folder
DirectoryInfo[] locations = MainSessionFolder.GetDirectories(); // Get all locations

foreach(var location in locations) // for every location
{
    DirectoryInfo[] TestFolders = location.GetDirectories(); // get test folders in that location
    foreach (var TestFolder in TestFolders) // for every test folder
    {
        if(SelectedTest.Name == TestFolder.Name) // check it it's what we want to rename
        Directory.Move(TestFolder.FullName, TestFolder.Name.Replace(SelectedTest.Name, NewName)); // rename it
    }

    FileInfo[] AllFiles = location.GetFiles(); // get all files in that location
    foreach (var ThisFile in AllFiles) // for every file in that location
    {
        if (SelectedTest.Name == ThisFile.Name) // check
            File.Move(SelectedTest.Name, NewName); // rename
    }
}

它在DirectoryInfo.move 上弹出一个错误(不是FileInfo.move,很奇怪,因为错误是文件)说:

“System.IO.IOException”类型的异常 ....
..当文件已经存在时无法创建文件..

【问题讨论】:

  • text 的值是多少?您是否在调试器中运行它以确保您没有尝试将两个不同的文件夹重命名为相同的名称?
  • @Dstanley 'text' 现在在帖子中是 'NewName' 是用户输入的字符串。绝对不会发生,因为一次只有一个文件夹,而且只会发生一次

标签: c# rename fileinfo directoryinfo system.io.fileinfo


【解决方案1】:

听起来你从和到的移动指向同一个位置。

尝试暂时将您的 Directory.Move 语句分解为更小的部分,然后逐步检查所有值是否符合您的预期。

string target = TestFolder.Name.Replace(SelectedTest.Name, NewName);

然后检查TestFolder.FullName、TestFolder.Name、SelectedTest.Name、NewName、target的值

检查它们是否符合您的期望,并在资源管理器中检查目标目录尚不存在。

希望能让您了解发生了什么问题。

【讨论】:

  • 绝对有帮助。转储我错过的(可能还没有午餐?)。原来两者都应该是 Directory.move 上的 FullName。此外,没有 File.FullName,所以我不得不使用它而不是最后一行: File.Move(location.FullName + "\\" + SelectedTest.Name + ".png", location.FullName + "\ \" + 新名称 + ".png")。并且因为 debuggin,已经在 bin/debug 中创建了一个文件夹,并且正在弹出一个错误。我没有在我的实际目录中工作,而是在 bin/debug cz Name 而不是 FullName 上工作。编辑您的答案,以便我标记它。谢谢:)
  • 啊,太好了,很高兴它有帮助。我已经更新了答案以反映问题更新。我认为这是您正在寻找的唯一更新?如果您想要包含该解决方案的解决方案,作为您问题的更新可能会更好(如果您愿意,我可以将其添加到答案中 - 只需让我知道您使用的确切语法)。
猜你喜欢
  • 2014-11-24
  • 2016-08-24
  • 1970-01-01
  • 2014-06-15
  • 2013-08-05
  • 2014-09-09
  • 1970-01-01
  • 2018-01-24
  • 1970-01-01
相关资源
最近更新 更多