【问题标题】:Load a file from Asset using Xamarin android使用 Xamarin android 从 Asset 加载文件
【发布时间】:2016-07-21 12:46:53
【问题描述】:

我想从资产加载文件,我找到了解决方案,但使用的是 Java。如何将以下 Java 代码转换为 c#。

public String loadKMLFromAsset() {

    String kmlData = null;
    try {

        InputStream is = getAssets().open("yourKMLFile");

        int size = is.available();

        byte[] buffer = new byte[size];

        is.read(buffer);

        is.close();

        kmlData = new String(buffer, "UTF-8");


    } catch (IOException ex) {
        ex.printStackTrace();
        return null;
    }
    return kmlData;

}

【问题讨论】:

  • 我建议你接受@mmushtaq,因为它是正确的。

标签: c# xamarin.android assets


【解决方案1】:

使用AssetManager

// Read the contents of our asset
string content;
AssetManager assets = this.Assets;
using (StreamReader sr = new StreamReader (assets.Open ("read_asset.txt")))
{
    content = sr.ReadToEnd ();
}

【讨论】:

  • 我看到这是直接从 Xamarin 文档中提取的:developer.xamarin.com/guides/android/application_fundamentals/… 减少此代码以直接使用活动的 Assets 属性会有什么问题吗?
  • 我需要什么 import 或 using 语句才能完成这项工作?对我来说,Visual Studio 无法识别 AssetManager
  • 这似乎假设您继承自 Activity。如果继承自Instrumentation,我们如何访问 AssetManager?
  • 这是直接从文档中提取的,并没有多大帮助。问题是支持参考是什么,因为没有它们,代码就会失败。
【解决方案2】:

如果您正在处理 db、kml、shapefile、视频格式等文件,请使用 BinaryReader 而不是 streamReader。StreamReader 仅读取字符串或纯文本,因此在读取二进制文件时可能会跳过某些内容,因为streamreader不会逐字节读取

【讨论】:

    【解决方案3】:

    此代码将资产文件写入移动文件系统中的文件:

     if (!System.IO.File.Exists("yourKMLFile_mobile"))
            {
    
                    var s = Resources.OpenRawResource(Resource.Raw.yourKMLFile);
    
                    FileStream writeStream = new FileStream("yourKMLFile_mobile", FileMode.OpenOrCreate, FileAccess.Write);
                    ReadWriteStream(s, writeStream);
                }  
    

    【讨论】:

    • 我认为你会混淆这个问题,因为你的答案很好,如果他想读取原始文件而不是资产文件。请检查其他答案。
    猜你喜欢
    • 1970-01-01
    • 2019-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-03
    • 2015-06-11
    • 1970-01-01
    相关资源
    最近更新 更多