How can I save the settings in the IsolatedStorage while BackgroundAudioPlayer's instance is active?

柔情痞子 提交于 2019-12-01 14:14:47

I agree that Background Audio is a breast. Whenever using any background agent you cannot rely on the ApplicationSettings to be synced. If you want to have settings saved and accessed from the UI (app) and background (audio agent) you should save a file. You can serialize the settings using Json.Net and save a file to a known location. Here is sample of what is might look like

// From background agent
var settings = Settings.Load();
if(settings.Foo)
{
    // do something
}

And here is a sample Settings File. The settings would need to be saved on a regular basis.

public class Settings
{
    private const string FileName = "shared/settings.json";

    private Settings() { }

    public bool Foo { get; set; }

    public int Bar { get; set; }

    public static Settings Load()
    {
        var storage = IsolatedStorageFile.GetUserStoreForApplication();
        if (storage.FileExists(FileName) == false) return new Settings();

        using (var stream = storage.OpenFile(FileName, FileMode.Open, FileAccess.Read))
        {
            using (var reader = new StreamReader(stream))
            {
                string json = reader.ReadToEnd();
                if (string.IsNullOrEmpty(json) == false)
                {
                    return JsonConvert.DeserializeObject<Settings>(json);
                }
            }
        }
        return new Settings();
    }

    public void Save()
    {
        var storage = IsolatedStorageFile.GetUserStoreForApplication();
        if(storage.FileExists(FileName)) storage.DeleteFile(FileName);
        using (var fileStream = storage.CreateFile(FileName))
        {
            //Write the data
            using (var isoFileWriter = new StreamWriter(fileStream))
            {
                var json = JsonConvert.SerializeObject(this);
                isoFileWriter.WriteLine(json);
            }
        }
    }
}

I personally have a FileStorage class that I use for saving/loading data. I use it everywhere. Here it is (and it does use the Mutex to prevent access to the file from both background agent and app). You can find the FileStorage class here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!