当前位置:编程学习 > wap >>

利用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))
                        {
                            //读取文件 www.zzzyk.com
                            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();
                    }
                }

 

摘自  Spider_net
补充:移动开发 , Windows Phone ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,