使用Xamarin android从Asset加载文件

时间:2016-07-21 12:46:53

标签: c# xamarin.android assets

我想从Asset加载一个文件,我找到了解决方案但是使用了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;

}

3 个答案:

答案 0 :(得分:5)

使用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 ();
}

答案 1 :(得分:0)

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

答案 2 :(得分:-1)

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

 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);
            }