Silverlight之獨立存儲(10)

獨立存儲

代碼下載

1.        獨立存儲

獨立存儲是一種數據存儲機制,它在代碼與保存的數據之間定義了標準化的關聯方式,從而提供隔離性和安全性。同時,標準化也提供了其他好處。管理員可以使用旨在操作獨立存儲的工具來配置文件存儲空間、設置安全策略及刪除未使用的數據。通過獨立存儲,代碼不再需要使用唯一的路徑來指定文件系統中的安全位置,同時可以保護數據免遭只具有獨立存儲訪問權限的其他應用程序的損壞。不再需要指示應用程序的存儲區域位置的硬編碼信息。

2.       代碼實現例子關鍵代碼

IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();

StringBuilder sb = new StringBuilder();

            //創建文件夾

            store.CreateDirectory("dir1");

            stringsub11 = Path.Combine("dir1", "SubDir11");

            stringsub12 = Path.Combine("dir1", "SubDir12");

            stringsub13 = Path.Combine("dir1", "SubDir13");

            store.CreateDirectory(sub11);

            store.CreateDirectory(sub12);

            store.CreateDirectory(sub13);

 

            store.CreateDirectory("dir2");

            store.CreateDirectory("dir2\\sub21");

            store.CreateDirectory("dir3");

 

            //創建文件

            IsolatedStorageFileStreamf1 = store.CreateFile(Path.Combine(sub11,"InTheRoot1.txt"));

            f1.Close();

            IsolatedStorageFileStreamf2 = store.CreateFile("InTheRoot12.txt");

            f2.Close();

            IsolatedStorageFileStreamf3 = store.CreateFile("InTheRoot13.txt");

            f3.Close();

 

 

 

            //得到文件夾

            string[]dirs = store.GetDirectoryNames();

            string[]subdirs = store.GetDirectoryNames(Path.Combine("dir1","*"));

 

 

            //得到文件

            string[]files = store.GetFileNames();

            stringsearchpath = Path.Combine(sub11, "*.*");

            string[]filesInSubDirs = store.GetFileNames(searchpath);

 

            //寫文件

            strings = "InTheRoot12.txt";

            if(store.FileExists(s))

            {

                try

                {

                    using(StreamWriter sw =newStreamWriter(store.OpenFile(s,FileMode.Open, FileAccess.Write)))

                    {

                        sw.WriteLine("滾滾長江東逝水!");

                    }

                }

                catch(IsolatedStorageException ex)

                {

                }

            }

            //讀文件

            try

            {

                using(StreamReader reader =new StreamReader(store.OpenFile(s,FileMode.Open,FileAccess.Read)))

                {

                    stringcontents = reader.ReadToEnd();

                    sb.AppendLine(s + "內容:");

                    sb.AppendLine(contents);

                }

            }

            catch(IsolatedStorageException ex)

            {

                sb.AppendLine(ex.Message);

            }

            //刪除文件,刪除文件夾

            store.DeleteFile(Path.Combine(sub11,"InTheRoot1.txt"));

            store.DeleteDirectory(sub11);

            //store.Remove();

 代碼下載

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章