Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamarin common Xamarin.Forms code across Android/iOS

I'm looking to create a Xamarin Forms PCL in Visual Studio 2015 that represents common application code for a Xamarin Android project and Xamarin iOS project (but NOT anything else, ie: Windows or Windows phone). I am currently using PCL profile 111 which is what is created by the provided Xamarin template.

All was fine until I came across support for System.IO.FileStream. Based on this article (in the Saving and Loading file section): https://developer.xamarin.com/guides/xamarin-forms/working-with/files/

Both Android and iOS can use much of System.IO right out of the box, and this is evident in my Android and iOS projects where I can use FileStream identically to read/write files.

Since the code is identical, it would make a lot more sense to maintain it in a single place, but I can't seem to track down a profile (or visual studio template) that will do this, any ideas?

I have additionally looked through here: http://blog.stephencleary.com/2012/05/framework-profiles-in-net.html

but the Portable Class Library profiles table doesn't mention Xamarin/Android/iOS.

Is there simply not a PCL profile any narrower than 111 which can provide what I want? Is my only option to use a DependencyService setup? Maybe a Shared Code project would be cleaner?

EDIT: Although I mention FileStream as an example of what I'm trying to do, I would like to solve the problem of maintaining any common code for Android/iOS (and only those platforms, not Windows/Windows Phone/Silverlight/ASP.NET etc) for any case where Android and iOS support a feature using common code, but one of those other platforms does not.


1 Answers

You can use PCLStorage Library for cross platform IO:

public async Task PCLStorageSample()
{
    IFolder rootFolder = FileSystem.Current.LocalStorage;
    IFolder folder = await rootFolder.CreateFolderAsync("MySubFolder",
        CreationCollisionOption.OpenIfExists);
    IFile file = await folder.CreateFileAsync("answer.txt",
        CreationCollisionOption.ReplaceExisting);
    await file.WriteAllTextAsync("42");
}
like image 136
Giorgi Avatar answered Dec 31 '25 20:12

Giorgi