Question

I've been trying to implement this example using C# and Monodroid, but am having difficulties reading and writing an Asset file:

http://docs.xamarin.com/android/advanced_topics/using_android_assets

I am using the emulator, not a device.

First of all, I am having trouble finding the namespace for Assets.Open. What I ultimately found was

const string lfn  = MyAssetFile.txt;
System.IO.StreamReader(Android.Content.Res.Resources.System.Assets.Open(lfn);

Is this the correct namespace?

Second of all, my Asset file is marked as AndroidAsset and "Copy Always" in the VS "Properties" pane, but my attempts to read the file always fail (File Not Found) using this statement:

string  settings = "";
using (StreamReader sr = new System.IO.StreamReader (Android.Content.Res.Resources.System.Assets.Open(lfn))) settings   =   sr.ReadToEnd();

Do I have my VS settings wrong so that the asset file not being copied onto the emulator, or is it being copied OK but my code to open/read it is wrong?

Was it helpful?

Solution

You must use:

const string lfn = "MyAssetFile.txt";
string settings = string.Empty;

// context could be ApplicationContext, Activity or
// any other object of type Context
using (var input = context.Assets.Open(lfn))
using (StreamReader sr = new System.IO.StreamReader(input))
{
    settings = sr.ReadToEnd();
}

If I remember correctly, as I haven't got an IDE at the moment, Android.Content.Res.Resources.System.Assets references the Android assets not your project assets. You want to use your projects assets so you need to use the AssetManager from your Activities or Contexts.

For example: the Activity class has a property called Assets. This is what you use. OR you use a View's Context.Assets property.

OTHER TIPS

Or just simply add at the top:

using System.IO;

and it will work.

Xamarin team forget sometimes to mention using stuff.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top