Xamarin在共享项目中读取文件

Xamarin在共享项目中读取文件,xamarin,readfile,filenotfoundexception,shared-project,Xamarin,Readfile,Filenotfoundexception,Shared Project,我正在尝试读取共享项目中的文件 var currentPath = Environment.CurrentDirectory; var filename = Path.Combine(currentPath, "File.txt"); var content = File.ReadAllText(filename); return content; 如果我在iOS中启动我的应用程序,这可以正常工作,但在Android中我会遇到Fi

我正在尝试读取共享项目中的文件

        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

或者,您可以尝试从
目录.GetCurrentDirectory()获取当前目录
method(在
System.IO
名称空间中)

没有环境。Datadirectory可用这可能是android特有的原因。你能试试
Directory.GetCurrentDirectory()?
我仍然得到FilenotFoundException