欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2022-09-21 11:42:32
最近手上的一个项目需要用到IsolatedStorageFile来做数据持久化存储,使用的时候遇到几个问题总结一下 首先写文件的代码: 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.2cto.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