From 792dcffdf64ef8c36c053d9de1985ce64727107e Mon Sep 17 00:00:00 2001 From: Gregory Oschwald Date: Mon, 29 Jun 2015 15:45:40 -0700 Subject: [PATCH] Allow delete/renaming of memory-mapped files --- MaxMind.Db/MemoryMapReader.cs | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/MaxMind.Db/MemoryMapReader.cs b/MaxMind.Db/MemoryMapReader.cs index 12b05d3..0e7961c 100644 --- a/MaxMind.Db/MemoryMapReader.cs +++ b/MaxMind.Db/MemoryMapReader.cs @@ -17,17 +17,25 @@ public MemoryMapReader(string file) Length = (int) fileInfo.Length; - var mmfName = fileInfo.FullName.Replace("\\", "-"); + // Ideally we would use the file ID in the mapName, but it is not + // easily available from C#. + var mapName = $"{fileInfo.FullName.Replace("\\", "-")}-{Length}"; lock (FileLocker) { try { - _memoryMappedFile = MemoryMappedFile.OpenExisting(mmfName, MemoryMappedFileRights.Read); + _memoryMappedFile = MemoryMappedFile.OpenExisting(mapName, MemoryMappedFileRights.Read); } catch (Exception ex) when (ex is IOException || ex is NotImplementedException) { - _memoryMappedFile = MemoryMappedFile.CreateFromFile(file, FileMode.Open, - mmfName, fileInfo.Length, MemoryMappedFileAccess.Read); + using ( + var stream = new FileStream(file, FileMode.Open, FileAccess.Read, + FileShare.Delete | FileShare.Read)) + { + + _memoryMappedFile = MemoryMappedFile.CreateFromFile(stream, mapName, Length, + MemoryMappedFileAccess.Read, null, HandleInheritability.None, false); + } } }