内存映射文件实例
需引入的命名空间
using System.IO;
using System.IO.MemoryMappedFiles;
1、写二进制数据到本地文件,这里没有用内存映射文件写文件,可以自己写一个
View Code
string path = Directory.GetCurrentDirectory() + @"\HistoryQuote\" + "AUDUSD" + ".data"; FileStream fs = new FileStream(path, FileMode.Create); //初始化FileStream对象 BinaryWriter bw = new BinaryWriter(fs); //创建BinaryWriter对象 StringBuilder sbQuote = new StringBuilder(); foreach (var item in historyPriceList) { sbQuote.Append(item.PriceDate.ToString("yyyy-MM-dd,HH:mm") + "," + item.OpenPrice + "," + item.High + "," + item.Low + "," + item.ClosePrice + ";"); } bw.Write(AesEncryption.AesEncryData(sbQuote.ToString())); bw.Close(); //关闭BinaryWriter对象 fs.Close(); //关闭文件流
2.用内存映射文件类,读取本地文件
View Code
//文件路径 path = Directory.GetCurrentDirectory() + @"\HistoryQuote\" + "AUDUSD" + ".data"; //内存映射文件类 MemoryMappedFile memoryFile = MemoryMappedFile.CreateFromFile(path, FileMode.Open); //保存读取到的信息 StringBuilder sb = new StringBuilder(); using (MemoryMappedViewStream Stream = memoryFile.CreateViewStream()) { BinaryReader reader = new BinaryReader(Stream); string quote = string.Empty; try { do { quote = reader.ReadString(); if (string.IsNullOrEmpty(quote) == false) { sb.Append(quote); } } while (string.IsNullOrEmpty(quote) == false); } catch (Exception ex) { } }
这里没有用
MemoryMappedViewAccessor.WriteArray/ReadArray 方法是因为它需要保存和读取
struct类型的数据,数据量较大时占用太大的磁盘空间,占用太大客户的磁盘空间不是我们的初衷和解决方案。
项目里面的东西太乱就不提供源码了。