一聚教程网:一个值得你收藏的教程网站

热门教程

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

时间:2022-06-26 00:19:10 编辑:袖梨 来源:一聚教程网

 代码如下 复制代码
IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
                //如果是复写文件,那么在写之前最好把文件删掉,不然如果这次写入的文件大小,小于文件本身的大小,那么之前文件的数据还是存在的,在读取的时候就会出问题.
                if (myIsolatedStorage.FileExists(filename) == true)
                {
                    myIsolatedStorage.DeleteFile(filename);
                }
                using (IsolatedStorageFileStream stream = myIsolatedStorage.OpenFile(filename, FileMode.CreateNew))
                {
                    List favlist = new List();
                    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 Data = (List)JsonConvert.DeserializeObject>(result);
                            foreach (var d in Data)
                            {
                                //添加到listview数据源
                                FavData.Add(d);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                    finally
                    {
                        stream.Close();
                    }
                }

热门栏目