Montag, 3. Dezember 2012

Windows Phone 8–Usage of Windows.Storage

If you want to implement a file access operation for Windows 8 you have the spoilt of choice: Old style with System.IO.IsolatedStorage or new style with the new WinRT API and classes in the Windows.Storage namespace. The first one will work for Windows Phone 7 and the second one only for Windows Phone 8 but also for a Windows 8 operating system and Metro styled apps.

I tried both solutions and here are the two code fragments which loading a file in a folder and deserialize them to a List of type <T>:

The solution using Isolated Storage:

        public static List<T> LoadList<T>(string folderName, string dataName) where T : class
        {
            var retval = new List<T>();
 
            if (!IsoStore.DirectoryExists(folderName))
            {
                IsoStore.CreateDirectory(folderName);
            }
 
            string fileStreamName = string.Format("{0}\\{1}.dat", folderName, dataName);
 
            using (var stream = new IsolatedStorageFileStream(fileStreamName, FileMode.OpenOrCreate, IsoStore))
            {
                if (stream.Length > 0)
                {
                    var dcs = new DataContractSerializer(typeof(List<T>));
                    retval = dcs.ReadObject(stream) as List<T>;
                }
            }
            return retval;
        }

And the same with using the new WinRT API and the classes in the Storage namespace:

        public static async Task<List<T>> LoadList<T>(string folderName, string dataName) where T : class
        {
            StorageFolder applicationFolder = ApplicationData.Current.LocalFolder;
 
            if (!await applicationFolder.FolderExistsAsync(folderName))
            {
                applicationFolder.CreateFolderAsync(dataName);
            }
            var retval = new List<T>();
 
            string fileStreamName = string.Format("{0}\\{1}.dat", folderName, dataName);
 
            if (await applicationFolder.FileExistsAsync( fileStreamName))
            {
 
                IStorageFile storageFile = await applicationFolder.GetFileAsync(fileStreamName);
 
                using (var inStream = await storageFile.OpenSequentialReadAsync())
                {
                    var serializer = new DataContractSerializer(typeof(List<T>));
                    retval = (List<T>)serializer.ReadObject(inStream.AsStreamForRead());
                }
            }
            return retval;
        }

Keine Kommentare:

Kommentar veröffentlichen