CreateFileMapping, MapViewOfFile 实现文件共享 (.net4.0 built-in)
.NET 4.0 以前是这么做的.
http://www.cnblogs.com/read-acquisitions-docs/archive/2009/11/27/1612214.html
现在....
class Program { static void Main(string[] args) { string file = @"C:\Users\user\Desktop\gts.txt"; int length = (int)new FileInfo(file).Length; using (var mmf = MemoryMappedFile.CreateFromFile( file, FileMode.Open, "my_gts", //共享内存在进程中的名字 length, //内存中分配大小, 太大会报内存不足, 不要超过需要读的block size就行,file size 更不行了 MemoryMappedFileAccess.ReadWrite //按需设置, 否则下面的code会报UnauthorizedAccessException )) { long offset = 0; int len = 10; byte[] b = new byte[len]; mmf.CreateViewStream().Read(b, 0, len); //在这里需要处理\0 一下 当长度和预期不一样的时候 string s = Encoding.Default.GetString(b); using (var accessor = mmf.CreateViewAccessor(offset , 10)) { UseDefinedNoReferenceMemberObject obj = new UseDefinedNoReferenceMemberObject(); obj.val = 1; obj.ch = 'g'; //看类型大小, 比如int是4,写入后记事本打开看是4个方块, 其他参阅C++ struct sizeof 补齐方式 accessor.Write<UseDefinedNoReferenceMemberObject>(0, ref obj); accessor.Read<UseDefinedNoReferenceMemberObject>(0, out obj); } } } struct UseDefinedNoReferenceMemberObject { public int val; public char ch; } }