Often we need to distribute some files together with our App like a prepopulated database, settings files, image etc. To do this there are basically three methods:
Embedded Resoures
- Quite good for Images like icons
- read only
- not directly accessable for file IO
- Can be accessed from PCL Files
- App has to be rebuilt
As Android Assets / iOS bundled Resource
- read only, so you have to copy them somewhere else if you want to have write access
- not accessible from PCL without Dependency Service
- App has to be rebuilt
- Has to be added to each platform project differently
Android
- read only
- not directly accessable for file
Example of reading a JSON File:
using (var reader = new StreamReader(assets.Open("SampleData.json")))
{
var json = new JsonSerializer();
list = (List)json.Deserialize(reader, typeof(List));
}
iOS
- read only
- directly accessible for file
using (var reader = new StreamReader(File.Open("./Samples/SampleData.json", FileMode.Open,FileAccess.Read))) { var json = new JsonSerializer(); list = (List)json.Deserialize(reader, typeof(List)); } return list;
Download from server at first startup
IMHO the most flexible solution.
- App does not have to be rebuilt
- writeable
- directly accessable for file IO
- can also be used to update an installed App
Often people shy way from this as it seems a lot of effort especially if you have a lot of files.
Luckily I happen to have published just yesterday a class calles FileStorage which offers a needful function called PopulateDataFolderFromZipUri
public async Task PopulateDataFolderFromZipUri(string uri,
string outFolder)
which will download a ZIP file from uri and extract it to outFolder which path is relative to your app's data directory