So I am re writing a routine to rename stuff. My Folder tree structure looks similar to this:
Folder -> Folder(s) -> Folder(s) + ImageFile(s)
Session -> Location(s) -> Test(s) + Images
All locations have the same Tests and renaming one must rename all. Also, Every Image has a related folder named the same as that image. So Images "one", "two", "three" will have folders "one", "two", "three" together in the same directory (location).
I am using this code to rename:
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
}
}
It pops an error on the DirectoryInfo.move
(not FileInfo.move
, weird because error says file) saying:
An exception of type 'System.IO.IOException' ....
.. Cannot create a file when that file already exists ..
It sounds like your move from and to are pointing to the same location.
Try temporarily breaking down your Directory.Move statement into smaller parts and step through to check the all values are what you expect.
string target = TestFolder.Name.Replace(SelectedTest.Name, NewName);
Then check the values of TestFolder.FullName, TestFolder.Name, SelectedTest.Name, NewName, target
Check they're what you expect, and also check in explorer that the target directories don't already exist.
Should hopefully give you an idea of what is going wrong.