參考資料: http://blog.csdn.net/bitfan/article/details/4438458 所謂記憶體映射文件,其實就是在記憶體中開闢出一塊存放數據的專用區域,這區域往往與硬碟上特定的文件相對應。進程將這塊記憶體區域映射到自己的地址空間中,訪問它就象是訪問普通的記憶體一樣。 在.NE ...
參考資料: http://blog.csdn.net/bitfan/article/details/4438458
所謂記憶體映射文件,其實就是在記憶體中開闢出一塊存放數據的專用區域,這區域往往與硬碟上特定的文件相對應。進程將這塊記憶體區域映射到自己的地址空間中,訪問它就象是訪問普通的記憶體一樣。
在.NET中,使用MemoryMappedFile對象表示一個記憶體映射文件,通過它的CreateFromFile()方法根據磁碟現有文件創建記憶體映射文件,調用這一方法需要提供一個與磁碟現有文件相對應的FileStream對象。
需要保存的類:
[Serializable] public class MyImg { public Image img; public string name; }View Code
MMF定義:
public class MMF { private MemoryMappedFile file = null; private MemoryMappedViewStream strem = null; private MemoryMappedViewAccessor acces = null; public MMF() { file = MemoryMappedFile.CreateOrOpen("myMMF", 1024 * 1024, MemoryMappedFileAccess.ReadWrite); strem = file.CreateViewStream(); acces = file.CreateViewAccessor(); } public void Write(int value) { acces.Write(0, value); } public int Read() { int value; acces.Read(0, out value); return value; } public void WriteClass(MyImg img) { IFormatter format = new BinaryFormatter(); format.Serialize(strem, img); } public MyImg ReadClass() { IFormatter format = new BinaryFormatter(); return format.Deserialize(strem) as MyImg; } }View Code
界面代碼:
private void button1_Click(object sender, EventArgs e) { using (OpenFileDialog dlg = new OpenFileDialog()) { dlg.Filter = "*.png|*.png"; if (dlg.ShowDialog() == DialogResult.OK) { this.pictureBox1.Image = Image.FromFile(dlg.FileName); this.label1.Text = Path.GetFileNameWithoutExtension(dlg.FileName); } } } private void button2_Click(object sender, EventArgs e) { MyImg img = new MyImg() { img = this.pictureBox1.Image, name = this.label1.Text }; myFile.WriteClass(img); } private void button3_Click(object sender, EventArgs e) { MyImg img = myFile.ReadClass(); this.pictureBox1.Image = img.img; this.label1.Text = img.name; } private void button4_Click(object sender, EventArgs e) { label2.Text = myFile.Read().ToString(); } private void button5_Click(object sender, EventArgs e) { myFile.Write(int.Parse(this.textBox1.Text)); }View Code
參考資料: http://blog.csdn.net/bitfan/article/details/4438458