Search code examples
c#.netmemory-mapped-files

How to have shared read-only access to a memory mapped file


While using a memory mapped file to read in a filestream as fast as possible in .net, I ran into the issue of IOExceptions due to file locking with two processes reading the same file.

There are several factory methods for producing a memory mapped file, how do I allow shared readonly access?


Solution

  • Here is a simplified factory method for creating a readonly memory mapped file to a path:

    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);
    
    }
    

    To create and use the full stream:

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