在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 存储信息
原文:https://www.cnblogs.com/lonelyxmas/p/10582724.html