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