C#中的独立存储器,映射内存使用方法
独立存储器和映射内存都是用来处理程序数据问题。独立存储器可以用来临时保存程序的一些不重要数据,映射内存文件则可以用来解决程序数据读取的问题。当程序在运行过程中需要加载大量的外部数据时,用它来做一个数据缓存区域将是一个不错的选择。
独立存储器
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();
}
}