uriToFile function

String uriToFile(
  1. String uri
)

Converts a file:// URI back to a file path (omp's uriToFile).

Tolerates lax servers that send raw paths or unencoded #/?: anything that does not parse cleanly falls back to a lenient manual conversion.

Implementation

String uriToFile(String uri) {
  if (!uri.startsWith('file://')) return uri;
  var rest = uri.substring('file://'.length);
  // Drop a host component (`file://host/path`); keep the leading slash.
  if (!rest.startsWith('/')) {
    final slash = rest.indexOf('/');
    rest = slash == -1 ? '/' : rest.substring(slash);
  }
  String path;
  try {
    path = Uri.decodeComponent(rest);
  } on Object {
    path = rest;
  }
  // `/C:/...` → `C:/...`.
  if (RegExp(r'^/[a-zA-Z]:[\\/]').hasMatch(path)) {
    path = path.substring(1);
  }
  return path;
}