forceRenameDirectoryPreserveContents function
Implementation
Future<void> forceRenameDirectoryPreserveContents(
String oldPath, String newPath) async {
try {
final oldDirectory = Directory(oldPath);
final newDirectory = Directory(newPath);
const tempDirectoryPath = 'temp';
final tempDirectory = Directory(tempDirectoryPath);
// Check if the old directory exists
if (await oldDirectory.exists()) {
// Check if the new directory already exists
if (await newDirectory.exists()) {
print(
'A directory with the new name already exists. Moving contents to a temporary directory...');
await removeDirectory(newPath);
// Create a temporary directory to hold the contents of the new directory
if (!await tempDirectory.exists()) {
await tempDirectory.create(recursive: true);
}
// Move contents of the existing new directory to the temporary directory
await moveContents(newDirectory, tempDirectory);
// Rename the old directory to the new path
// Rename the old directory to the new path
await oldDirectory.rename(newPath);
// Move contents from the temporary directory back to the renamed directory
await moveContents(tempDirectory, newDirectory);
// Delete the temporary directory
await tempDirectory.delete(recursive: true);
print('Directory renamed and contents preserved.');
} else {
// Simply rename the old directory if the new directory does not exist
await oldDirectory.rename(newPath);
print('Directory renamed successfully.');
}
} else {
print('Old directory does not exist.');
}
} catch (e) {
print('Error renaming directory: $e');
}
}