/// <summary> /// Factory method to create a file mapping for read only access. /// </summary> /// <param name="fileName">The name of the file to open memory mapped.</param> /// <returns></returns> public static RawMemoryMapping <T> OpenRead(string fileName) { if (fileName == null) { throw new ArgumentNullException("fileName"); } var mapping = new RawMemoryMapping <T>(); mapping.teaFile = TeaFile <T> .OpenRead(fileName); try { FileStream fs = mapping.teaFile.Stream as FileStream; if (fs == null) { throw new InvalidOperationException("TeaFile used for MemoryMapping is not a file stream but memory mapping requires a file."); } mapping.mappingHandle = UnsafeNativeMethods.CreateFileMapping( fs.SafeFileHandle, IntPtr.Zero, MapProtection.PageReadOnly, 0, 0, null); if (mapping.mappingHandle.IsInvalid) { throw new Win32Exception(); } try { mapping.mappingStart = UnsafeNativeMethods.MapViewOfFile( mapping.mappingHandle, MapAccess.FileMapRead, 0, 0, IntPtr.Zero); if (mapping.mappingStart == (byte *)0) { throw new Win32Exception(); } mapping.itemAreaStart = mapping.mappingStart + mapping.teaFile.ItemAreaStart; mapping.itemAreaEnd = mapping.itemAreaStart + mapping.teaFile.ItemAreaSize; } catch { if (UnsafeNativeMethods.CloseHandle(mapping.mappingHandle) == 0) { // our view mapping failed above, but we still had a good mapping handle, so if // closing failed, we should check why throw new Win32Exception(); } mapping.mappingHandle = null; throw; } return(mapping); } catch { mapping.Dispose(); throw; } }
/// <summary>Opens a memory mapping of the file using unsafe memory mapping. </summary> /// <param name="path">path of the file. </param> /// <returns>An instance of <see cref="RawMemoryMapping{T}"/> providing access to the items in the file. </returns> /// <remarks> /// Compared to <see cref="OpenRawMemoryMapping"/>, this raw access performs much better. /// </remarks> public static RawMemoryMapping <T> OpenRawMemoryMapping(string path) { return(RawMemoryMapping <T> .OpenRead(path)); }