Search code examples
jsonxamarinxml-serializationportable-class-library.net-standard

Saving Data locally on a .net Standard app


I want to serialize data on my .net Standard app into a local file and I would like to avoid sqlite if possible.

The standard recommendation for cross plattform app seems to have been PCL Storage, but according to this link, PCL Storage is not maintained anymore, offers no .net Standard support and the alternative PCLExt is not mature.

Can you tell me if it is possible to simply serialize my data e.g. with json?

Tank you very much!


Solution

  • You do not have complete access over the OS's filesystem and platform-specific features like Android's ContentResolver, but for basic file read/write within your app's sandbox (or external filesystem if your app has access to it) .NetStandard 2.0 works fine, and thus works for storing and retrieving text-based files for serializing/deserializing Json.

    Example, if you have a Xamarin.Forms based solution and add a .NetStandard 2.0 library project to the solution and also add Newtonsoft.Json to it. You could create these functions in it:

    .NetStandard library functions:

    public static class Common
    {
        public static void WriteFile(string fileName, Tuple<string, string> obj)
        {
            var path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            File.WriteAllText(Path.Combine(path, fileName), JsonConvert.SerializeObject(obj));
        }
    
        public static Tuple<string, string> ReadFile(string fileName)
        {
            var path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            return JsonConvert.DeserializeObject<Tuple<string, string>>(File.ReadAllText(Path.Combine(path, fileName));
        }
    }
    

    Now in your Xamarin.Forms project (.NetStandard * Shared project), reference the project/library you created you could do something like this:

    ReadWriteCommand = new Command(() =>
    {
        var someObj = Tuple.Create("Stack", "Overflow");
    
        Common.WriteFile("SushiHangover.txt", someObj);
        var readSomeObj = Common.ReadFile("SushiHangover.txt");
        if ((someObj.Item1 != readSomeObj.Item1) || (someObj.Item2 != readSomeObj.Item2))
            throw new Exception();
    });