Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 534
jbtule Avatar asked Dec 04 '25 01:12

jbtule


1 Answers

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
}
like image 56
jbtule Avatar answered Dec 05 '25 15:12

jbtule



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!