龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > 移动开发 > Windows phone 开发 >

WP7独立存储IsolatedStorageFile读写文件实现程序

时间:2013-01-03 09:27来源:未知 作者:admin 点击:
分享到:
代码如下 复制代码 IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication(); //如果是复写文件,那么在写之前最好把文件删掉,不然如果这次写入的文件大小,小于文件本身的大
 代码如下 复制代码
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();
                    }
                }


精彩图集

赞助商链接