如何共享对内存映射文件的只读访问权限

jbt*_*ule 2 .net c# memory-mapped-files

在使用内存映射文件尽可能快地在.net中IOException读取文件流时,由于两个读取同一文件的进程锁定了文件,因此我遇到了s 的问题。

有几种用于生成内存映射文件的工厂方法,如何允许共享readonly访问?

jbt*_*ule 5

这是用于创建指向路径的只读内存映射文件的简化工厂方法:

public static MemoryMappedFile MemFile(string path)
{
     return MemoryMappedFile.CreateFromFile(
               //include a readonly shared stream
               File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read),
               //not mapping to a name
               null,
               //use the file's actual size
               0L, 
               //read only access
               MemoryMappedFileAccess.Read, 
               //not configuring security
               null,
               //adjust as needed
               HandleInheritability.None,
               //close the previously passed in stream when done
               false);

}
Run Code Online (Sandbox Code Playgroud)

要创建和使用完整流:

using (var memFile = MemFile(path))
using (var stream = memFile.CreateViewStream(0L, 0L, MemoryMappedFileAccess.Read))
{
     //do stuff with your stream
}
Run Code Online (Sandbox Code Playgroud)