首页 文章

Windows 8 App本地存储

提问于
浏览
3

我正在尝试使用C#开发Windows 8应用程序,我需要在本地设置中存储两个列表(字符串和日期时间)

List<string> names = new List<string>();
List<DateTime> dates = new List<DateTime>();

我根据这个页面使用了LocalSettings:http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh700361

Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;

但是当我存储列表并从保存的设置中取回列表时,我遇到了问题 .

您可以通过发送几行来存储和检索字符串List和DateTime列表类型对象(或存储此类数据的其他方法)来帮助您 .

谢谢 .

3 回答

  • 3

    这是一个名为Windows 8 Isolated storage的库,它使用XML序列化 . 您可以存储 object 以及 List<T> . 用法也很简单 . 只需在项目中添加DLL即可获得存储数据的方法 .

    public class Account
    {
       public string Name { get; set; }
       public string Surname{ get; set; }
       public int Age { get; set; }
    }
    

    保存在隔离存储中:

    Account obj = new Account{ Name = "Mario ", Surname = "Rossi", Age = 36 };
    var storage = new Setting<Account>();          
    storage.SaveAsync("data", obj);
    

    从隔离存储加载:

    public async void LoadData()
    {    
        var storage = new Setting<Account>();
        Account obj = await storage.LoadAsync("data");    
    }
    

    此外,如果要存储列表:在隔离存储中保存列表:

    List<Account> accountList = new List<Account>();
    accountList.Add(new Account(){ Name = "Mario", Surname = "Rossi", Age = 36 });
    accountList.Add(new Account(){ Name = "Marco", Surname = "Casagrande", Age = 24});
    accountList.Add(new Account(){ Name = "Andrea", Surname = "Bianchi", Age = 43 });
    
    var storage = new Setting<List<Account>>(); 
    storage.SaveAsync("data", accountList );
    

    从隔离存储加载列表:

    public async void LoadData()
    {    
        var storage = new Setting<List<Account>>();    
        List<Account> accountList = await storage.LoadAsync("data");    
    }
    
  • 0

    请查看此示例,它演示了如何将集合保存到应用程序存储:http://code.msdn.microsoft.com/windowsapps/CSWinStoreAppSaveCollection-bed5d6e6

  • 1

    试试这个存储:

    localSettings.Values["names"] = names 
    localSettings.Values["dates"] = dates
    

    这个:

    dates = (List<DateTime>) localSettings.Values["dates"];
    

    编辑:看起来我错了,你只能用这种方式存储基本类型 . 因此,您可能必须使用MemoryStream将所有内容序列化为byte []并仅保存其缓冲区 .

相关问题