Windows Phone开发之独立存储的两种使用方法小结

来源:互联网 发布:php config 的位置 编辑:程序博客网 时间:2024/06/16 18:19

Windows Phone开发独立存储两种使用方法总结如下:
以前有个错误的理解,因为一直用模拟器开发小案例,模拟器重启之后独立存储的数据都会被删除,
就错误的以为真机可能也会出现这样的问题。
其实,不是这样的。真相是:
模拟器每次启动都会重新初始化,当然不会保存。但在真实手机上会永永保存,就像硬盘,但一旦恢复出厂设置或者刷机,也会丢失。
另外,由于WP每个应用程序都分配专用空间,所以,如果程序从手机上卸载,隔离存储中的数据也会丢失。
所以说,在WP手机上原来保存的数据存储在独立存储区域还是很不错的选择。

方法一:IsolatedStorageSetting

 //保存数据IsolatedStorageSettings setting = IsolatedStorageSettings.ApplicationSettings;                string mykey = "myValue";                string myvalues = "";                if (setting.Contains(mykey))                {                    setting[mykey] = myTextBox.Text;                }                else                {                    setting.Add(mykey, myvalues);                }                setting.Save();//读取数据IsolatedStorageSettings setting = IsolatedStorageSettings.ApplicationSettings;                if (setting.Contains("myValue"))                {                    myTextBlock.Text = setting["myValue"].ToString();                }//删除数据myTextBox.Text = "";                IsolatedStorageSettings iso = IsolatedStorageSettings.ApplicationSettings;                string mykey = "myValue";                if (iso.Contains(mykey)){                    iso.Remove(mykey);                }

方法二:IsolatedStorageFile

//保存数据IsolatedStorageFile isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication();                string fileName = "myFile.txt";                                  using (var file = new IsolatedStorageFileStream(fileName,FileMode.OpenOrCreate,isolatedStorageFile))                    {                        using (var writer = new StreamWriter(file))                        {                            writer.WriteLine(myTextBox.Text);                                                   }                    }//读取数据IsolatedStorageFile isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication();                string fileName = "myFile.txt";                if(isolatedStorageFile.FileExists(fileName)){                    using (var file =new IsolatedStorageFileStream(fileName,FileMode.Open,isolatedStorageFile))                    {                        using (var reader = new StreamReader(file))                        {                            myTextBlock.Text = reader.ReadLine();                        }                    }                }//删除数据myTextBox.Text = "";IsolatedStorageFile isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication();                if (isolatedStorageFile.FileExists("myFile.txt")) {                    isolatedStorageFile.DeleteFile("myFile.txt");                }

补充常用方法如下:

IsolatedStorage:    WeatherInfo temp = null;WeatherInfo w = null;IsolatedStorageSettings iss = IsolatedStorageSettings.ApplicationSettings;    if (iss.TryGetValue("WeatherInfo", out temp))//取值先判断值是否存在               { w = temp;}代码说明:iss.TryGetValue("WeatherInfo", out temp)返回Boolean类型,temp为输出,“WeatherInfo”为Key值。



 

原创粉丝点击