17.17. Obtaining a Safer File Handle
Problem
You want more security when manipulating an unmanaged file handle than a simple IntPtr can provide.
Solution
Use the Microsoft.Win32.SafeHandles.SafeFileHandle object to wrap an existing unmanaged file handle:
public static void WriteToFileHandle(IntPtr hFile)
{
// Wrap our file handle in a safe handle wrapper object.
using (Microsoft.Win32.SafeHandles.SafeFileHandle safeHFile =
new Microsoft.Win32.SafeHandles.SafeFileHandle(hFile, true))
{
// Open a FileStream object using the passed-in safe file handle.
using (FileStream fileStream = new FileStream(safeHFile,
FileAccess.ReadWrite))
{
// Flush before we start to clear any pending unmanaged actions.
fileStream.Flush();
// Operate on file here.
string line = "Using a safe file handle object";
// Write to the file.
byte[] bytes = Encoding.ASCII.GetBytes(line);
fileStream.Write(bytes,0,bytes.Length);
}
}
// Note that the hFile handle is invalid at this point.
}The SafeFileHandle constructor takes two arguments. The first is an IntPtr that contains a handle to an unmanaged resource. The second argument is a Boolean value, where true indicates that the handle will always be released during finalization, and false indicates that the safeguards that force the handle to be released during finalization are turned off. Unless you have an extremely good reason to turn off these safeguards, it is recommended that you always set this Boolean value to true.
Discussion
A SafeFileHandle object contains a ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access