/// <summary>
/// Used by the 2 Create factory method groups. A null fileHandle specifies that the
/// memory mapped file should not be associated with an existing file on disk (i.e. start
/// out empty).
/// </summary>
private static SafeMemoryMappedFileHandle CreateCore(
SafeFileHandle?fileHandle, string?mapName, HandleInheritability inheritability,
MemoryMappedFileAccess access, MemoryMappedFileOptions options, long capacity, long fileSize)
{
Debug.Assert(fileHandle is null || fileSize >= 0);
Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(inheritability);
if (fileHandle != null)
{
VerifyMemoryMappedFileAccess(access, capacity, fileSize);
}
SafeMemoryMappedFileHandle handle = fileHandle != null?
Interop.CreateFileMapping(fileHandle, ref secAttrs, GetPageAccess(access) | (int)options, capacity, mapName) :
Interop.CreateFileMapping(new IntPtr(-1), ref secAttrs, GetPageAccess(access) | (int)options, capacity, mapName);
int errorCode = Marshal.GetLastPInvokeError();
if (!handle.IsInvalid)
{
if (errorCode == Interop.Errors.ERROR_ALREADY_EXISTS)
{
handle.Dispose();
throw Win32Marshal.GetExceptionForWin32Error(errorCode);
}
}
else // handle.IsInvalid
{
handle.Dispose();
throw Win32Marshal.GetExceptionForWin32Error(errorCode);
}
return(handle);
}