1. 程式人生 > >使用 IsolatedStorageFileStream 存儲信息

使用 IsolatedStorageFileStream 存儲信息

異常 實例 [] 機制 style public 數據 != users

在C#中還有一種叫做IsolatedStorage的存儲機制,他存儲信息的方式類似於我們的cookie, IsolatedStorage存儲獨立於每一個application,換句話說我們加載多個應用程序是他們不會相互影響,我們這樣就可以在 下次運行的時從IsolatedStorage中提取一些有用的數據,這對我們來說是很好的一件事吧~

使用islatedstorage也十分簡單,不廢話了 還是上個實例看吧.

先獲取一個IsolatedStorage文件對象.

隨後我們將創獲取IsolatedStorageFileStream對象,再以文件流的形式寫入和讀取

註:(using System.IO.IsolatedStorage;using System.IO;)

 static void Main(string[] args)
        {
            string fileName = "test.txt";
            SaveData("測試內容.", fileName);
            string content = LoadData(fileName);
            Console.ReadKey();
        }
        //保存
        static void SaveData(string _data, string _fileName)
        {
            
//如果嘗試使用此方法 ClickOnce 或基於 Silverlight 的應用程序之外,你將收到IsolatedStorageException異常,因為不能確定調用方的應用程序標識。 //using (IsolatedStorageFile myIsf = IsolatedStorageFile.GetUserStoreForApplication()) using (IsolatedStorageFile isf = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null
, null)) { //var availableFreeSpace = isf.AvailableFreeSpace.ToString() + " bytes";//這裏是剩余空間 //var quota = isf.Quota.ToString() + " bytes";//這裏是當前的限額 //var usedSpace = (isf.Quota - isf.AvailableFreeSpace).ToString() + " bytes";//這裏是用戶已經使用的空間 //if (true == isf.IncreaseQuotaTo(1048576 * 2))//將限額增加到2MB(註: 這裏單位是bytes) 新配額必須大於舊配額 //{ // quota = isf.Quota.ToString() + " bytes";// 限額 //} //else //{ // var Text = "限額更改失敗."; //} using (IsolatedStorageFileStream isolatedStorageFileStream = new IsolatedStorageFileStream(_fileName, FileMode.OpenOrCreate, isf)) { //獲取文件路徑 //string filePath = isolatedStorageFileStream.GetType().GetField("m_FullPath", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(isolatedStorageFileStream).ToString(); using (StreamWriter mySw = new StreamWriter(isolatedStorageFileStream)) { mySw.BaseStream.Seek(0, SeekOrigin.End); //追加(寫入位置) mySw.Write(_data); mySw.Close(); } } } } //讀取 static string LoadData(string _fileName) { string data = String.Empty; using (IsolatedStorageFile myIsf = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null)) { using (IsolatedStorageFileStream isolatedStorageFileStream = new IsolatedStorageFileStream(_fileName, FileMode.Open, myIsf)) { //獲取文件路徑 // string filePath = isolatedStorageFileStream.GetType().GetField("m_FullPath", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(isolatedStorageFileStream).ToString(); using (StreamReader sr = new StreamReader(isolatedStorageFileStream)) { string lineOfData = string.Empty; while ((lineOfData = sr.ReadLine()) != null) data += lineOfData; } } } return data; } }

參考:

IsolatedStorageFile.GetUserStoreForApplication

使用 IsolatedStorageFileStream 存儲信息