How to open the file system of a volume in CreateFile?
Asked Answered
A

2

8

The MSDN page on CreateFile says: The string "\\.\C:\" can be used to open the file system of the C: volume. However, the following code always returns an error : ERROR_PATH_NOT_FOUND.

HANDLE h = CreateFile(L"\\\\.\\C:\\", FILE_READ_ATTRIBUTES, 
    FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE, 0, OPEN_EXISTING, 0, 0);

How should I pass the arguments correctly?

Albertina answered 8/1, 2013 at 3:4 Comment(3)
What do you want to do with the resulting handle?Pram
I just wonder why it didn't work as expected. My initial intent was to list files under the root directory.Albertina
in my case, I get INVALID_HANDLE_VALUEJazmin
P
8

If you wanted a volume handle (for use with I/O control codes) you would have needed to drop the trailing slash.

In order to get a handle to the root directory, you need to keep the trailing slash and pass the FILE_FLAG_BACKUP_SEMANTICS flag in the dwFlagsAndAttributes argument. This is documented on the MSDN page under the heading "Directories". For example, this is what you want to do if you're planning to call GetFileInformationByHandle or GetFileInformationByHandleEx.

Ordinarily, however, you wouldn't open a handle to the root directory in order to list the files. Instead, you would use FindFirstFile/FindNextFile or one of the related functions.

Pram answered 8/1, 2013 at 4:15 Comment(3)
Why does this work? C: isn't defined in the device namespace. Surely you'd have to use L"\\??\\C:"Launderette
@Lewis, I've never found any documentation that clearly explains the way the device namespace works, but see this answer on Super User. C: is an alias in GLOBAL?? as can be confirmed using WinObj.Pram
that's interesting, maybe it searches both global and the device namespace. I will have to look at the source code of the object manager function that does it I thinkLaunderette
S
1

Try dropping the trailing slash:

L"\\\\.\\C:"
Sato answered 8/1, 2013 at 3:39 Comment(1)
I think you misconstrued what I mean. I know it will be OK if the trailing backslash is dropped. However, although the documentation explicitly declares the trailing backslash is a valid argument, CreateFile always returns an error. That's the key point of my question.Albertina

© 2022 - 2024 — McMap. All rights reserved.