move function

void move(
  1. String from,
  2. String to, {
  3. bool overwrite = false,
})

Move a file from one location to another.

This function moves a single file from from to to. If to is a directory, the file will be moved into that directory with its original name. If a cross-device move is needed, the function will copy and then delete.

Parameters:

  • from: Source file path
  • to: Destination path (can be a file path or directory)
  • overwrite: If true, overwrites existing files (defaults to false)

Throws:

  • Exception if the source file doesn't exist
  • Exception if the target already exists and overwrite is false
  • Exception if there are insufficient permissions

Example:

move('/path/to/source.txt', '/path/to/destination.txt');
move('/path/to/source.txt', '/path/to/directory/'); // Moves into directory
move('/path/to/source.txt', '/path/to/existing.txt', overwrite: true);

Implementation

void move(String from, String to, {bool overwrite = false}) {
  // Validate input
  if (from.isEmpty) {
    StatusHelper.failed('Source path cannot be empty.');
  }
  if (to.isEmpty) {
    StatusHelper.failed('Destination path cannot be empty.');
  }
  if (!exists(from)) {
    StatusHelper.failed('The source ${truepath(from)} does not exist.');
  }

  var dest = to;

  if (isDirectory(to)) {
    dest = p.join(to, p.basename(from));
  }

  final absoluteDest = truepath(dest);

  if (!overwrite && exists(absoluteDest)) {
    StatusHelper.failed('The destination $absoluteDest already exists.');
  }

  try {
    File(from).renameSync(dest);
  } on FileSystemException catch (e) {
    // Check if this is a cross-device move (Invalid cross-device link)
    if (e.osError?.errorCode == 18 || e.message.contains('cross-device')) {
      // We can't move files across partitions, so do a copy/delete
      try {
        copy(from, dest, overwrite: overwrite);
        delete(from);
      } catch (copyError) {
        StatusHelper.failed(
            'Failed to move ${truepath(from)} to $absoluteDest via copy/delete: $copyError');
      }
    } else {
      StatusHelper.failed(
          'Failed to move ${truepath(from)} to $absoluteDest: ${e.message}');
    }
  } catch (e) {
    StatusHelper.failed(
        'An unexpected error occurred moving ${truepath(from)} to $absoluteDest: $e');
  }
}