/// <summary> /// Pass the file handle to the <see cref="System.IO.FileStream"/> constructor. /// The <see cref="System.IO.FileStream"/> will close the handle. /// </summary> public static SafeFileHandle CreateFileHandle( string filePath, CreationDisposition creationDisposition, FileAccess fileAccess, FileShare fileShare) { filePath = CheckAddLongPathPrefix(filePath); // Create a file with generic write access var fileHandle = PInvokeHelper.CreateFile( filePath, fileAccess, fileShare, IntPtr.Zero, creationDisposition, 0, IntPtr.Zero); // Check for errors. var lastWin32Error = Marshal.GetLastWin32Error(); if (fileHandle.IsInvalid) { throw new Win32Exception( lastWin32Error, string.Format( Resources.ErrorCreatingFileHandle, lastWin32Error, filePath, CheckAddDotEnd(new Win32Exception(lastWin32Error).Message))); } // Pass the file handle to FileStream. FileStream will close the handle. return(fileHandle); }