【问题标题】:how to access files in xamarin.android. And also in Visual Studio Solution explorer where should i place the file in order to locate it in my code如何访问 xamarin.android 中的文件。还有在 Visual Studio 解决方案资源管理器中,我应该将文件放在哪里以便在我的代码中找到它
【发布时间】:2021-02-05 16:03:08
【问题描述】:

下面的代码尝试访问 Asset 文件夹中名为 zimbabwe 的文件

var fileContent = File.ReadAllText("Asset/zimbabwe.shp")

我应该如何访问 xamarin.android 中的文件?还有在 Visual Studio 解决方案资源管理器中,我应该将文件放在哪里以便在我的代码中找到它?

【问题讨论】:

    标签: c# .net xamarin.android


    【解决方案1】:

    在 Xamarin.Android 项目中,Assets 使用 AssetManager 读取。可以通过访问 Android.Content.Context 的 Assets 属性(例如 Activity)来获得 AssetManager 的实例。

    例如:

    string content;
    AssetManager assets = this.Assets;
    using (StreamReader sr = new StreamReader (assets.Open ("zimbabwe.shp")))
    {
        content = sr.ReadToEnd ();
    }
    

    在 Xamarin.Forms 项目中,您还可以将任何文件添加到 Android 项目的 Assets 文件夹中,并将 Build Action 标记为 AndroidAsset 以与 OpenAppPackageFileAsync 一起使用。

    using (var stream = await FileSystem.OpenAppPackageFileAsync(templateFileName))
    {
      using (var reader = new StreamReader(stream))
      {
        var fileContents = await reader.ReadToEndAsync();
      }
    }
    

    【讨论】:

    • @LloydNyahwai 如果对您有帮助,您可以将其标记为接受答案,那么它可以帮助其他人。
    猜你喜欢
    • 2011-03-27
    • 2018-06-07
    • 2015-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多