Search code examples
c#c++winapiiopinvoke

using CreateFile on c# returns isInvalid = true


I'm using CreateFile as shown below, and keep getting isInvalid = true, no meter what I do, however, the error code returning from "Marshal.GetLastWin32Error" is changing according to the path I’m trying to access.

Here are the paths and their corresponding error codes:

  1. @lpFileName = "c:\” -> 3
  2. @lpFileName = "\\127.0.0.1\share\" -> 123
  3. @lpFileName = "c:\share\" -> 5

Obviously "c:\" does exists, and as far as I know "\\127.0.0.1\share\" is a valid UNC and I gave every possible right to everyone on the target computer, both NTFS and share. None of those make sense.

My system is Server 2008R2 Help please.

CreateFile:

[DllImport("kernel32.dll", SetLastError = true)]
    static extern SafeFileHandle CreateFile(
        LPCTSTR lpFileName,
        DWORD dwDesiredAccess,
        DWORD dwShareMode,
        LPSECURITY_ATTRIBUTES lpSecurityAttributes,
        DWORD dwCreationDisposition,
        DWORD dwFlagsAndAttributes,
        HANDLE hTemplateFile
        );

With the flags below:

DWORD dwIoControlCode,
        LPCTSTR lpFileName,
        DWORD dwDesiredAccess = GENERIC_READ | GENERIC_WRITE,
        DWORD dwShareMode = FILE_SHARE_WRITE|FILE_SHARE_READ,
        LPSECURITY_ATTRIBUTES lpSecurityAttributes = default(LPSECURITY_ATTRIBUTES),
        DWORD dwCreationDisposition = OPEN_EXISTING,
        DWORD dwFlagsAndAttributes = 0,
        HANDLE hTemplateFile = default(IntPtr)
        )

and flag values:

 public const DWORD
        GENERIC_READ = 0x80000000,
        GENERIC_WRITE = 0x40000000,
        FILE_SHARE_WRITE = 0x2,
        FILE_SHARE_READ = 0x1,
        OPEN_EXISTING = 0x3;

Solution

  • http://msdn.microsoft.com/en-us/library/windows/desktop/aa363858%28v=vs.85%29.aspx

    CreateFile function (Windows)

    Directories

    To open a directory using CreateFile, specify the FILE_FLAG_BACKUP_SEMANTICS flag as part of dwFlagsAndAttributes.