コード例 #1
0
        internal unsafe MemoryMapFile(String fileName, String fileMappingName) {
            //
            // Use native API to create the file directly.
            //
            SafeFileHandle fileHandle = Win32Native.UnsafeCreateFile(fileName, FileStream.GENERIC_READ, FileShare.Read, null, FileMode.Open, 0, IntPtr.Zero);
            int lastError = Marshal.GetLastWin32Error();
            if (fileHandle.IsInvalid) 
            {
                BCLDebug.Assert(false, "Failed to create file " + fileName + ", GetLastError = " + lastError);
                throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("InvalidOperation_UnexpectedWin32Error"), lastError));
            }

            int highSize;
            int lowSize = Win32Native.GetFileSize(fileHandle, out highSize);
            if (lowSize == Win32Native.INVALID_FILE_SIZE)
            {
                BCLDebug.Assert(false, "Failed to get the file size of " + fileName + ", GetLastError = " + lastError);
                throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("InvalidOperation_UnexpectedWin32Error"), lastError));
            }

            fileSize = (((long) highSize) << 32) | ((uint) lowSize);

            if (fileSize == 0)
            {
                // we cannot map zero size file. the caller should check for the file size.
                fileHandle.Close();
                return;
            }
            
            SafeFileMappingHandle fileMapHandle = Win32Native.CreateFileMapping(fileHandle, IntPtr.Zero, PAGE_READONLY, 0, 0, fileMappingName);
            fileHandle.Close();
            lastError = Marshal.GetLastWin32Error();
            if (fileMapHandle.IsInvalid) {
                BCLDebug.Assert(false, "Failed to create file mapping for file " + fileName + ", GetLastError = " + lastError);
                throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("InvalidOperation_UnexpectedWin32Error"), lastError));
            }
                                    
            viewOfFileHandle = Win32Native.MapViewOfFile(fileMapHandle, SECTION_MAP_READ, 0, 0, UIntPtr.Zero);
            lastError = Marshal.GetLastWin32Error();
            if (viewOfFileHandle.IsInvalid) {
                BCLDebug.Assert(false, "Failed to map a view of file " + fileName + ", GetLastError = " + lastError);
                throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("InvalidOperation_UnexpectedWin32Error"), lastError));
            }

            bytes = (byte*)viewOfFileHandle.DangerousGetHandle ();

            fileMapHandle.Close();
        }