moveDir function
Move a directory from one location to another.
This function moves an entire directory tree from from to to.
If a cross-device move is needed, the function will copy the tree and then delete the original.
Parameters:
from: Source directory pathto: Destination directory path (must not exist)
Throws:
- Exception if the source directory doesn't exist
- Exception if the source is not a directory
- Exception if the destination already exists
- Exception if there are insufficient permissions
Example:
await moveDir('/path/to/source/dir', '/path/to/destination/dir');
Implementation
Future<void> moveDir(String from, String to) async {
// Validate input
if (from.isEmpty) {
StatusHelper.failed('Source directory path cannot be empty.');
}
if (to.isEmpty) {
StatusHelper.failed('Destination directory path cannot be empty.');
}
final absoluteFrom = truepath(from);
final absoluteTo = truepath(to);
if (!exists(absoluteFrom)) {
StatusHelper.failed('The source directory $absoluteFrom does not exist.');
}
if (!isDirectory(absoluteFrom)) {
StatusHelper.failed(
'The source $absoluteFrom is not a directory. Use move for files.');
}
if (exists(absoluteTo)) {
StatusHelper.failed(
'The destination directory $absoluteTo already exists.');
}
try {
Directory(absoluteFrom).renameSync(absoluteTo);
} on FileSystemException catch (e) {
// Check if this is a cross-device move
if (e.osError?.errorCode == 18 || e.message.contains('cross-device')) {
try {
// Create destination directory
Directory(absoluteTo).createSync(recursive: true);
// Copy the entire tree
copyTree(absoluteFrom, absoluteTo, includeHidden: true);
// Delete the original
Directory(absoluteFrom).deleteSync(recursive: true);
} catch (copyError) {
StatusHelper.failed(
'Failed to move directory $absoluteFrom to $absoluteTo via copy/delete: $copyError');
}
} else {
StatusHelper.failed(
'Failed to move directory $absoluteFrom to $absoluteTo: ${e.message}');
}
} catch (e) {
StatusHelper.failed(
'An unexpected error occurred moving directory $absoluteFrom to $absoluteTo: $e');
}
}