Reputation: 161
First of all, I'm developing a WindowsPhone8.1 app which has a JSON (name, telephone number, email-...) file from the web. I store this JSON data in a list (contact is a class which has the parameters from the JSON.
I want to store (local no Cloud) this list on my WindowsPhone (its a List with marked favorites, not the whole list).
I tried it with StorageFolder and StorageFile, unfortunately, I failed. Got a problem with deleting and loading the files.
Developing in Microsoft Visual Studio Premium 2013 Update 3 with C#, Xaml.
Upvotes: 2
Views: 296
Reputation: 6222
I use this class, you need Json package which is available via nuget.
class StorageService : IConfigurationService
{
readonly StorageFolder _local = ApplicationData.Current.LocalFolder;
public async void Save<T>(string key, T obj)
{
var json = JsonConvert.SerializeObject(obj);
var dataFolder = await _local.CreateFolderAsync("DataFolder",
CreationCollisionOption.OpenIfExists);
var file = await dataFolder.CreateFileAsync(key,
CreationCollisionOption.ReplaceExisting);
await FileIO.WriteTextAsync(file, json);
}
public async Task<T> Load<T>(string key)
{
try
{
var dataFolder = await _local.GetFolderAsync("DataFolder");
var file = await dataFolder.OpenStreamForReadAsync(key);
string json;
using (var streamReader = new StreamReader(file))
{
json = streamReader.ReadToEnd();
}
return JsonConvert.DeserializeObject<T>(json);
}
catch (Exception)
{
return default(T);
}
}
}
Upvotes: 2