Tobiuo
Tobiuo

Reputation: 323

How to access a file from the android project in Xamarin

I have two files in my android project in Xamarin which I would like to access and turn into a byte array. Something like: byte[] fileInBytes = File.ReadAllBytes(Path.Combine("Models", "myFile.dat"));

The two files that I would like at access

But I haven't been able to access them with the methods I've tried so far. I've tried accessing them by using assembly.GetName().Name + "." + "Models.myFile.dat") but with no luck. I found a lot of examples on how to read from a file in the Assets folder, but I don't need to read, I need the file as bytes.

At the moment the files build action is set to "Embedded Resource", but I don't know if that is correct. Please help.

Upvotes: 1

Views: 2082

Answers (2)

York Shen
York Shen

Reputation: 9084

How to access a file from the android project in Xamarin

You should put your myFile.dat file into Assets folder, as the document said :

Assets provide a way to include arbitrary files like text, xml, fonts, music, and video in your application. If you try to include these files as "resources", Android will process them into its resource system and you will not be able to get the raw data. If you want to access data untouched, Assets are one way to do it.

When you need get bytes from the file :

AssetManager assets = this.Assets;
using (StreamReader sr = new StreamReader(assets.Open("myFile.dat")))
{
     byte[] bytes = default(byte[]);
     using (var memstream = new MemoryStream())
     {
         sr.BaseStream.CopyTo(memstream);
         bytes = memstream.ToArray();
     }
}

Upvotes: 4

Narendra Sharma
Narendra Sharma

Reputation: 682

Add the read permission in your manifest file

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

and every this will set to work.

Upvotes: 0

Related Questions