windows - 如何在 Dart SDK 的 Windows 中以字符串形式获取路径而无需前导 "slash"?

标签 windows path dart uri dart-sdk

import 'dart:io';

void main() {
  var path = Platform.script.path;
  print(path);
}

输出

/C:/Users/user/dart/test/bin/test.dart

但是我想要得到

C:/Users/user/dart/test/bin/test.dart

让操作系统特定路径准备好在此操作系统中使用的推荐方法是什么?

附言

如果我在不同的平台上运行测试代码,我会得到不同的结果。

所以,测试。

运行时:Dart SDK 版本 1.1.1(稳定版)

代码:

import 'dart:io';

void main() {
  var path = Platform.script.path;
  print(path);
  // From doc: Creates a new file URI from an absolute or relative file path.
  var uri = new Uri.file(path);
  print(uri.path);
}

Ubuntu 13.10:

/home/andrew/dart/test/bin/test.dart
/home/andrew/dart/test/bin/test.dart

Windows 7:

/C:/Users/user/dart/test/bin/test.dart
Breaking on exception: Illegal argument(s): Illegal character in path}
Unhandled exception:
Illegal argument(s): Illegal character in path}

这种行为使我无法编写跨平台代码。

最佳答案

此代码适用于所有平台。

import 'dart:io';

void main() {
  var path = Platform.script.toFilePath();
  print(path);
  var uri = new Uri.file(path);
  print(uri.toFilePath());
}

附言

类似的异常(Illegal character in path)在使用 scheme ""dart-ext"时会在 Dart SDK 中发生(在某些情况下):

Unhandled exception:
Unsupported operation: Illegal character in path}
#0      Uri._checkWindowsPathReservedCharacters.<anonymous closure> (dart:core/uri.dart:395)
#1      ListIterable.forEach (dart:_collection-dev/iterable.dart:39)
#2      Uri._checkWindowsPathReservedCharacters (dart:core/uri.dart:390)
#3      Uri._toWindowsFilePath (dart:core/uri.dart:1018)
#4      Uri.toFilePath (dart:core/uri.dart:992)
#5      _filePathFromUri (dart:builtin:249)
'package:dart_and_cpp_classes/src/cpp_extension.dart': error: line 3 pos 1: library handler failed
import "dart-ext:cpp_extension";
^
'package:dart_and_cpp_classes/cpp_extension.dart': error: line 3 pos 1: library handler failed
import 'package:dart_and_cpp_classes/src/cpp_extension.dart';
^
'file:///C:/Users/user/dart/dart_and_cpp_classes/bin/use_cpp_extension.dart': error: line 1 pos 1: library handler failed
import 'package:dart_and_cpp_classes/cpp_extension.dart';
^

关于windows - 如何在 Dart SDK 的 Windows 中以字符串形式获取路径而无需前导 "slash"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21207354/

相关文章:

linux - 选择路径cmd窗口中的最后一个目录

linux - 世界标准时间/格林威治标准时间 : Getting the Offset

flutter - 使用Flutter/Dart如何查询未构建窗口小部件的数据?

Flutter BlocBuilder 不调用新状态

windows - Windows 上 mDNS 的当前状态是什么?

windows - Jenkins 无法连接到存储库 : Command returned status code 128:

SVN - 更改工作副本以指向新的 svn 路径

c++ - #include c/c++中的绝对路径语法

bash - 递归地将文件放入Unix中的回收站

dart - 如何在pub中保留软件包名称?