isDirWritable function

bool isDirWritable(
  1. Directory directory, {
  2. bool? isDirExist,
})

Checks if a directory is writable by the current process.

It attempts to create and then clean up a temporary subdirectory inside directory.
If directory does not exist, it's first created and deleted to test write permissions on its parent.

Returns true if writable, false otherwise (e.g., permission denied, invalid path).

Implementation

bool isDirWritable(Directory directory, {bool? isDirExist}) {
  isDirExist ??= directory.existsSync();
  Directory? testDir;

  try {
    if (!isDirExist) {
      directory
        ..createSync(recursive: true)
        ..deleteSync();
      return true;
    }

    bool runing = true;
    while (runing) {
      final tempDirName = '._writable_test_${Random().nextInt(1000000)}';
      testDir = Directory('${directory.path}/$tempDirName');
      if (!testDir.existsSync()) {
        runing = false;
        testDir.createSync();
      }
    }

    return true;
  } catch (e) {
    return false;
  } finally {
    if (testDir != null && testDir.existsSync()) {
      try {
        testDir.deleteSync(recursive: true);
      } catch (e) {
        // print(e);
      }
    }
  }
}