Search code examples
vb.netwinapifile-iontfs

How to get the file handle in vb .net


I want to use the GetFileInformationByHandle function under kernel32.dll in order to get the NTFS unique file identifier. The function declaration is like this :

Declare Auto Function GetFileInformationByHandle Lib "kernel32.dll" _ 
(ByVal hFile As IntPtr, ByRef lpFileInformation As BY_HANDLE_FILE_INFORMATION) As Boolean

My question may sound stupid but, how do I get the file handle (hFile As IntPtr) for a given filename in visual basic ?


Solution

  • You can use the FileStream.SafeFileHandle property:

    Using fs As FileStream = New FileStream("c:\test.txt", FileMode.Create, FileAccess.Write)
        Dim hFile = fs.SafeFileHandle.DangerousGetHandle()
        ' do something
    End Using