How to Save Data in a Windows Phone App

Tags: Windows Phone, Storage, Development

I can't remember where I saw this first, but it has proven invaluable for storing data from Windows Phone Apps to the user's local storage.

    public static class IsolatedStorageOperations
    {
        public static async Task Save<T>(this T obj, string file)
        {
            await Task.Run(() =>
            {
                var storage = IsolatedStorageFile.GetUserStoreForApplication();
                IsolatedStorageFileStream stream = null;

                try
                {
                    stream = storage.CreateFile(file);
                    var serializer = new XmlSerializer(typeof(T));
                    serializer.Serialize(stream, obj);
                }
                finally
                {
                    if (stream != null)
                    {
                        stream.Close();
                        stream.Dispose();
                    }
                }
            });
        }

        public static async Task<T> Load<T>(string file)
        {
            var storage = IsolatedStorageFile.GetUserStoreForApplication();
            var obj = Activator.CreateInstance<T>();

            if (storage.FileExists(file))
            {
                IsolatedStorageFileStream stream = null;
                try
                {
                    stream = storage.OpenFile(file, FileMode.Open);
                    var serializer = new XmlSerializer(typeof(T));
                    obj = (T)serializer.Deserialize(stream);
                }
                catch (Exception ex)
                {
                    if (stream != null)
                    {
                        stream.Close();
                        stream.Dispose();
                    }
                    storage.DeleteFile(file);
                }
                finally
                {
                    if (stream != null)
                    {
                        stream.Close();
                        stream.Dispose();
                    }
                }
                return obj;
            }
            await obj.Save(file);
            return obj;
        }
    }

No Comments

Add a Comment