我正在尝试读取共享项目中的文件。
var currentPath = Environment.CurrentDirectory;
var filename = Path.Combine(currentPath, "File.txt");
var content = File.ReadAllText(filename);
return content;
如果我在 iOS 中启动我的应用程序,这工作正常,但在 Android 中我得到 FileNotFound 异常。
最佳答案
文件系统结构和底层 API 因平台而异。 Environment.CurrentDirectory
在 iOS 上存在,但在 Android 和 UWP 上都不存在,因此它将具有空值,因此无法找到该文件。
由于平台之间的文件系统差异很大,因此建议您将环境级文件访问代码抽象为平台特定项目而不是共享项目 - 尽管您可以使用编译器指令使其工作。
#if __ANDROID__
var currentPath = Environment.DataDirectory;
#endif
或者,您可以尝试从 Directory.GetCurrentDirectory();
方法(在 System.IO
命名空间中)获取当前目录
关于Xamarin 读取共享项目中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42507174/