Search code examples
c#oopcaching

How to cache data in C# in the simplest and most elegant way?


I am writing an audiobook app in C# .NET Framework. I need to store on user disc information about audiobooks' locations and last listened audiobooks. I'm looking for the simplest and the most elegant way to do it. As easy as it can be.

What is the best (safe and proper) way to do it? How you would do it?


Solution

  • A very simple way is to create a custom class that holds properties for each setting you want to persist between sessions. Then create an instance of this class and set the properties with the values you want to persist.
    Finally serialize the instance with a Json library transforming it in a string and save it to a location where you have read/write permissions.
    To retrieve the information just do the reverse, read from the file, deserialize the string into an instance of your setting class and then use it.

    So supposing a class like this:

    public class ApplicationSettings
    {
        public string LastBookName { get; set; }
        public List<string> PreviousTitles { get; set; }
    }
    

    You can have two helper methods like these one (making use of NewtonSoft.Json library NuGet here)

    public void SaveSettings(ApplicationSettings aps)
    {
        string json = JsonConvert.SerializeObject(aps);
        File.WriteAllText(@"E:\temp\savedsettings.json", json);
    }
    
    public ApplicationSettings LoadSettings()
    {
        string json = File.ReadAllText(@"E:\temp\savedsettings.json");
        return JsonConvert.DeserializeObject<ApplicationSettings>(json);
    }
    

    Now you just need to call these two methods in the appropriate points of your code.