Home > C#, Windows Phone > Salvate una lista di oggetti nell’IsolatedStorage

Salvate una lista di oggetti nell’IsolatedStorage

Ciao!

Ecco una comoda classe che ci permette di salvare una lista di oggetti in un file all’interno dell’IsolatedStorage di Windows Phone:

public class IsoStoreHelper
    {
        private static IsolatedStorageFile _isoStore;
        public static IsolatedStorageFile IsoStore
        {
            get { return _isoStore ?? (_isoStore = IsolatedStorageFile.GetUserStoreForApplication()); }
        }

        public static void SaveList<T>(string folderName, string dataName, ObservableCollection<T> dataList) where T : class
        {
            if (!IsoStore.DirectoryExists(folderName))
            {
                IsoStore.CreateDirectory(folderName);
            }

            string fileStreamName = string.Format("{0}\\{1}.dat", folderName, dataName);

            using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(fileStreamName, FileMode.Create, IsoStore))
            {
                DataContractSerializer dcs = new DataContractSerializer(typeof(ObservableCollection<T>));
                dcs.WriteObject(stream, dataList);
            }
        }

        public static ObservableCollection<T> LoadList<T>(string folderName, string dataName) where T : class
        {
            ObservableCollection<T> retval = new ObservableCollection<T>();

            string fileStreamName = string.Format("{0}\\{1}.dat", folderName, dataName);

            using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(fileStreamName, FileMode.OpenOrCreate, IsoStore))
            {
                if (stream.Length > 0)
                {
                    DataContractSerializer dcs = new DataContractSerializer(typeof(ObservableCollection<T>));
                    retval = dcs.ReadObject(stream) as ObservableCollection<T>;
                }
            }

            return retval;
        }

Bisogna ricordarsi di aggiungere una reference a System.Runtime.Serialization.

Per utilizzare questa classe, ecco un esempio:

      ObservableCollection<Prova> lista = new ObservableCollection<Prova>();
      ObservableCollection<Prova> listaTest = new ObservableCollection<Prova>();

      lista.Add(new Prova(){ nome = "Sergio" });
      lista.Add(new Prova(){ nome = "Fabio" });
      lista.Add(new Prova(){ nome = "Erika" });

      IsoStoreHelper.SaveList<Prova>("prova", "prova", lista);
      listaTest = IsoStoreHelper.LoadList<Prova>("prova", "prova");

Happy Coding!

Annunci
Categorie:C#, Windows Phone
  1. Kondor
    ottobre 9, 2012 alle 5:35 pm

    Io lo migliorerei così,giusto per non avere eccezioni se si ha necessità di invocare prima un Loade sopo un Save:

    public static List LoadList(string folderName, string dataName) where T : class
    {
    List retval = new List();

    string fileStreamName = string.Format(“{0}\\{1}.dat”, folderName, dataName);

    try
    {

    using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(fileStreamName, FileMode.OpenOrCreate, IsoStore))
    {
    if (stream.Length > 0)
    {
    DataContractSerializer dcs = new DataContractSerializer(typeof(List));
    retval = dcs.ReadObject(stream) as List;
    }
    }
    }
    catch (Exception)
    {
    SaveList(folderName, dataName, new List());
    }
    return retval;
    }

    • ottobre 11, 2012 alle 9:25 am

      grazie mille per l’implementazione!!! 🙂

  2. gennaio 17, 2013 alle 10:43 pm

    hi
    can u share with me, how to random image with array in WP? please help, thanks :’)

  3. maggio 19, 2013 alle 7:01 pm

    We all know that natural milk in mother’s is healthier for the newborn as it contains Lauric acid. The benefits of coconut oil are that unlike any other oils, the oil contains fewer calories and its fat content is easily converted into energy. As well as losing weight, the addition of this oil can also help to lower cholesterol and lower blood pressure.

  4. giugno 10, 2013 alle 2:00 am

    Some genuinely good posts for this site, thanks for contribution.

  5. marzo 5, 2014 alle 8:35 am

    Hi there! I could have sworn I’ve been to this website before but
    after reading through some of the post I realized it’s new to
    me. Anyhow, I’m definitely happy I found it and I’ll be
    bookmarking and checking back often!

  6. luglio 10, 2014 alle 2:03 pm

    Hi, I desire to subscribe for this web site to take most up-to-date updates, thus where can i do it please assist.

  7. ottobre 8, 2014 alle 2:40 pm

    Definitely believe that which you stated. Your favorite reason appeared to be on the internet the simplest thing to
    be aware of. I say to you, I certainly get irked while people think about worries that
    they plainly don’t know about. You managed to hit the nail
    upon the top and defined out the whole thing without having side effect , people can take a signal.
    Will likely be back to get more. Thanks

  1. No trackbacks yet.

Rispondi

Inserisci i tuoi dati qui sotto o clicca su un'icona per effettuare l'accesso:

Logo WordPress.com

Stai commentando usando il tuo account WordPress.com. Chiudi sessione / Modifica )

Foto Twitter

Stai commentando usando il tuo account Twitter. Chiudi sessione / Modifica )

Foto di Facebook

Stai commentando usando il tuo account Facebook. Chiudi sessione / Modifica )

Google+ photo

Stai commentando usando il tuo account Google+. Chiudi sessione / Modifica )

Connessione a %s...

%d blogger hanno fatto clic su Mi Piace per questo: