利用WP7独立存储IsolatedStorageFile读写文件

最近手上的一个项目需要用到IsolatedStorageFile来做数据持久化存储,使用的时候遇到几个问题总结一下

首先写文件的代码:

IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
                //如果是复写文件,那么在写之前最好把文件删掉,不然如果这次写入的文件大小,小于文件本身的大小,那么之前文件的数据还是存在的,在读取的时候就会出问题.
                if (myIsolatedStorage.FileExists(filename) == true)
                {
                    myIsolatedStorage.DeleteFile(filename);
                }
                using (IsolatedStorageFileStream stream = myIsolatedStorage.OpenFile(filename, FileMode.CreateNew))
                {
                    List<VideoItemData> favlist = new List<VideoItemData>();
                    foreach (var i in coll)
                    {
                        favlist.Add(i);
                    }
                    using (var str = new StreamWriter(stream))
                    {
                        str.Write(JsonConvert.SerializeObject(favlist));
                    }
                }

代码中的注释部分,一定要慎重.复写之前最好删掉文件,不然会因为数据不正确而导致读取的时候出错.而且这类错误很难排查.

然后是读文件的代码:

IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
                if (myIsolatedStorage.FileExists("fav.json") == true)
                {
                    //打开文件
                    IsolatedStorageFileStream stream = myIsolatedStorage.OpenFile("fav.json", FileMode.Open);
                    try
                    {
                        using (var sr = new StreamReader(stream))
                        {
                            //读取文件
                            string result = sr.ReadToEnd();
                            result = result.Trim();
                            sr.Close();
                            //反序列化为对象
                            List<VideoItemData> Data = (List<VideoItemData>)JsonConvert.DeserializeObject<List<VideoItemData>>(result);
                            foreach (var d in Data)
                            {
                                //添加到listview数据源
                                FavData.Add(d);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                    finally
                    {
                        stream.Close();
                    }
                }

 

来自WPDevN: http://www.wpdevn.com/showtopic-105.aspx

 

转载于:https://www.cnblogs.com/spidernet/archive/2012/04/19/2456439.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值