【问题标题】:Xamarin read a file in shared ProjectXamarin 读取共享项目中的文件
【发布时间】:2017-07-19 07:56:35
【问题描述】:

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

        var currentPath = Environment.CurrentDirectory;
        var filename = Path.Combine(currentPath, "File.txt");
        var content = File.ReadAllText(filename);
        return content;

如果我在 iOS 中启动我的应用程序,这工作正常,但在 Android 中我得到 FileNotFound 异常。

【问题讨论】:

    标签: xamarin readfile filenotfoundexception shared-project


    【解决方案1】:

    文件系统结构和底层 API 因平台而异。 Environment.CurrentDirectory在iOS上存在,但在Android和UWP上都不存在,所以它会有一个空值,因此找不到文件。

    由于平台之间的文件系统差异很大,因此建议您将环境级别文件访问代码抽象到平台特定项目而不是共享项目 - 尽管您可以使用编译器指令使其工作。

    #if __ANDROID__
    var currentPath = Environment.DataDirectory;
    #endif
    

    或者,您可以尝试从Directory.GetCurrentDirectory(); 方法(在System.IO 命名空间中)获取当前目录

    【讨论】:

    • 没有 Environment.Datadirectory 可用
    • 这是 android 特有的,这可能就是原因。你可以试试Directory.GetCurrentDirectory()?
    • 我仍然得到 FilenotFoundException
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多