獨立存儲器和映射內存都是用來處理程序數據問題。獨立存儲器可以用來臨時保存程序的一些不重要數據 ,映射內存文件則可以用來解決程序數據讀取的問題。當程序在運行過程中需要加載大量的外部數據時,用它 來做一個數據緩存區域將是一個不錯的選擇。
獨立存儲器
static void UserIsolationFile() { //this file was saved into the path: C:\Users\you account\AppData\Local\IsolatedStorage IsolatedStorageFile storFile = IsolatedStorageFile.GetUserStoreForDomain(); IsolatedStorageFileStream storStream = new IsolatedStorageFileStream("storagefile.txt", FileMode.Create, FileAccess.Write); StreamWriter writer = new StreamWriter(storStream); writer.WriteLine("You are dead!"); writer.Flush(); writer.Close(); storStream.Close(); storFile.Close(); IsolatedStorageFile storFile2 = IsolatedStorageFile.GetUserStoreForDomain(); string[] filenames = storFile2.GetFileNames(); foreach (string filename in filenames) { if (filename != "storagefile.txt") { continue; } using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("storagefile.txt", FileMode.Open)) { using (StreamReader reader = new StreamReader(stream)) { Console.WriteLine(reader.ReadToEnd()); } } } Console.ReadKey(); }
映射內存
這個東西怎麼感覺很像C呀,哈哈。如有程序需要頻繁的讀寫文本類文件可以這它來做一 個讀寫緩存提高程序的效率。
static void MappingMemory() { using(var mmFile=MemoryMappedFile.CreateFromFile("d:\\mappingmemory.txt" ,FileMode.Create ,"fileHandle",1024*1024)) { string valueToWrite = "Written to the mapped-memory file on "+ DateTime.Now.ToString(); var myAccessor = mmFile.CreateViewAccessor(); myAccessor.WriteArray<byte>(0, Encoding.ASCII.GetBytes(valueToWrite), 0 , valueToWrite.Length); var readOut = new byte[valueToWrite.Length]; myAccessor.ReadArray<byte>(0, readOut, 0, readOut.Length); Console.WriteLine("The data is:" + Encoding.ASCII.GetString(readOut)); Console.ReadKey(); } }