简体   繁体   中英

HANDLE (IntPtr) Obsolete, kernel32.dll, SafeFileHandle to IntPtr

I am in need of implementing a solution very similar to the one found here , written in 2009, to retrieve a unique identifier for a file. Specifically, I am looking at the answer's ApproachB() function and the following line (re-written a bit to reflect new C# capabilities):

var fi = new FileInfo(@"C:\Temp\testfile.txt");
var fs = fi.Open(FileMode.Open,FileAccess.Read,FileShare.ReadWrite);
WinAPI.GetFileInformationByHandle(fs.Handle, out objectFileInfo); // fs.Handle being the portion in question

The problem, here, is that GetFileInformationByHandle maps to an extern function imported from the "kernel32.dll". The signature of which is as follows:

[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool GetFileInformationByHandle(IntPtr hFile, out BY_HANDLE_FILE_INFORMATION lpFileInformation);

Type IntPtr maps well to the specified type in the above linked doc.s HANDLE . However, the Handle property on FileStream objects has been deprecated (made obsolete ) and replaced with SafeFileHandle which does not map to a IntPtr .

Is there a way to overcome this to where the extern definition can accept the type SafeFileHandle ? Or, is there another extern method that has been implemented for this purpose?

Change your PInvoke signature to

[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool GetFileInformationByHandle(SafeFileHandle hFile, out BY_HANDLE_FILE_INFORMATION lpFileInformation);

or keep it and call on your SafeFileHandle instance the method .DangerousGetHandle() which will return the IntPtr you are searching for. This method is implemented in the base class SafeHandle which is made for exactly that purpose.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM