While using a memory mapped file to read in a filestream as fast as possible in .net, I ran into the issue of IOException
s 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?
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
}