0

I need to call native Win32 API from .NET code which required file/directory handle. How do I get a handle for the directory?

To get a file handle I use the following code:

using (FileStream stream = File.Open(filePath, FileMode.Open...))
{
    var handle = stream.SafeFileHandle;
    /// Call Win32 API here
}
  1. How do I get a handle for a directory?
  2. Is there any better approach for getting the handle for files? I fill like using FileStream is confusing for those who will read this code.
IT Hit WebDAV
  • 5,652
  • 12
  • 61
  • 98
  • Does this answer your question? [Open Directory Using CreateFile](https://stackoverflow.com/questions/10198420/open-directory-using-createfile) – Klaus Gütter Aug 21 '20 at 06:36
  • @Klaus Gütter The answer says that administrative privileges are required. My app runs with minimum user permissions. Also File.Open() / FileStream.SafeFileHandle does not require admin privileges. So I guess there should a way to obtain a handle without admin permissions. – IT Hit WebDAV Aug 21 '20 at 06:51
  • Directory handles are different. See description of FILE_FLAG_BACKUP_SEMANTICS in [CreateFile documentation](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilew). Also this is relevant: https://learn.microsoft.com/en-us/windows/win32/fileio/obtaining-a-handle-to-a-directory – Klaus Gütter Aug 21 '20 at 06:54
  • @Klaus Gütter So to call GetFileTime() Win32 API for a file I do not need admin privileges. But to call it for a folder I need admin privileges. I am scratching my head. – IT Hit WebDAV Aug 21 '20 at 07:22
  • Im confused, you dont want to use FileStream and want to use raw api calls, so why not just use raw api calls to get the handle ? Also unless you have spent a lot of time in win32 api, i doubt the code will be more readable. Especially since you will need to PInvoke everything – TheGeneral Aug 21 '20 at 07:36
  • 1
    Also if you want to get the file time just call `FileInfo fi = new FileInfo("path"); fi.CreationTime;` It couldn't be easier to read – TheGeneral Aug 21 '20 at 07:39
  • 1
    Whether or not administrator privileges are required depends on the directory you want to open. The `GetFileTime` document mentions that the `hFile` must have `GENERIC_READ` access (use `CreateFile` with `dwDesiredAccess = GENERIC_READ` and `dwFlagsAndAttributes = FILE_FLAG_BACKUP_SEMANTICS`). If you do not have `GENERIC_READ` for the directory Access, you may need elevated permissions to get handle from `CreateFile`. – Drake Wu Aug 21 '20 at 07:58
  • @Drake Wu - MSFT Thank you! This brings us much closer to the point. I need to call CfUpdatePlaceholder(). And I finally found params for opening a folder and calling this function without admin privileges! – IT Hit WebDAV Aug 22 '20 at 06:58
  • You could feel free to share your own answer and [accept yourself](https://stackoverflow.blog/2009/01/06/accept-your-own-answers/) – Drake Wu Aug 24 '20 at 01:13

0 Answers0