create_ method

Future<void> create_()

Creates the File.

Implementation

Future<void> create_() async {
  if (Platform.isWindows) {
    // On Windows, \\?\ prefix causes issues if we use it to access a root volume without a trailing slash.
    // In other words, \\?\C: is not valid, but \\?\C:\ is valid. If we try to access \\?\C: without a trailing slash, following error is thrown by Windows:
    //
    // "\\?\C:" is not a recognized device.
    // The filename, directory name, or volume label syntax is incorrect.
    //
    // When recursively creating a [File] or [Directory] recursively using `dart:io`'s implementation, if the parent [Directory] does not exist, all the intermediate [Directory]s are created.
    // However, internal implementation of dart:io does not handle the case of \\?\C: (without a trailing slash) & fails with the above error.
    // To avoid this, we manually create the intermediate [Directory]s with the trailing slash.
    final file = File(addPrefix(path));
    final parent = Directory(addTrailingSlash(this.parent.path));

    // Case A.
    if (await file.exists_()) {
      return;
    }
    // Case B.
    if (await parent.exists_()) {
      await file.create();
      return;
    }
    // Case C.
    final parts = removePrefix(file.path).split(kPathSeparator);
    parts.removeLast();
    for (int i = 0; i < parts.length; i++) {
      final path = addTrailingSlash(
          addPrefix(parts.sublist(0, i + 1).join(kPathSeparator)));
      try {
        if (!await Directory(path).exists_()) {
          await Directory(path).create();
        }
      } catch (exception, stacktrace) {
        print(exception.toString());
        print(stacktrace.toString());
      }
    }
    await file.create();
  } else {
    try {
      await File(addPrefix(path)).create(recursive: true);
    } catch (exception, stacktrace) {
      print(exception.toString());
      print(stacktrace.toString());
    }
  }
}