vb.netcreatefilekernel32safefilehandle

CreateFile() Works in Windows XP but fails in Windows 7 return Handle Invalid


While trying to create a handler using CreateFile(), even when executing the application as administrator, I get the following error message: ‘The system could not find the specified file. (Exception from HRESULT: 0x80070002)":Nothing.’

Here is a sample of the code being used for this task:

Private Enum EFileAccess As System.Int32
        GENERIC_WRITE = &H40000000
End Enum

Friend Enum EFileShare        
    FILE_SHARE_READ = &H1
    FILE_SHARE_WRITE = &H2
End Enum

Friend Enum ECreationDisposition        
    OPEN_EXISTING = 3
End Enum

Friend Enum EFileAttributes
   FILE_FLAG_NO_BUFFERING = &H20000000
End Enum

<DllImport("kernel32.dll", SetLastError:=True, CharSet:=System.Runtime.InteropServices.CharSet.Auto)> _
    Private Shared Function CreateFile(ByVal lpFileName As String, _
                                ByVal dwDesiredAccess As EFileAccess, _
                                ByVal dwShareMode As EFileShare, _
                                ByVal lpSecurityAttributes As IntPtr, _
                                ByVal dwCreationDisposition As ECreationDisposition, _
                                ByVal dwFlagsAndAttributes As EFileAttributes, _
                                ByVal hTemplateFile As IntPtr) As Microsoft.Win32.SafeHandles.SafeFileHandle
    End Function

The path points to a matrix printer in a Windows Server 2003.

handle = CreateFile(\\brbhzpc001154\Epson_2180,
                                EFileAccess.GENERIC_WRITE,
                                EFileShare.FILE_SHARE_READ Or EFileShare.FILE_SHARE_WRITE,
                                IntPtr.Zero,
                                ECreationDisposition.OPEN_EXISTING,
                                EFileAttributes.FILE_FLAG_NO_BUFFERING,
                                IntPtr.Zero)

This application, when compiled works without any error in Windows XP, but when trying to execute in Windows 7, the error described above always happens.


Solution

  • There are solutions here suggesting that on Win7 changing OPEN_EXISTING to OPEN_ALWAYS will make it work on Win7, but with no explanation why.