
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
724
|
Chapter 12: Filesystem I/O
Solution
In order to use an unmanaged file handle to access a file, use the FileStream class.
The unmanaged file handle could have been generated using P/Invoke to open a file
and get the file handle. The code would then use a
FileStream object for writing
data, then flush and close the unmanaged file handle. This setup is illustrated by the
UsingAnUnmanagedFileHandle method shown in Example 12-8.
In the
UsingAnUnmanagedFileHandle method, we wrap the file handle in a
SafeFileHandle object and pass it as the first parameter, in a FileStream. Once we
have the file stream, we use its capabilities to write to the file handle. We get the
Example 12-8. UsingAnUnmanagedFileHandle method
public static void UsingAnUnmanagedFileHandle( )
{
IntPtr hFile = IntPtr.Zero;
// Create a file using unmanaged code.
hFile = FileInteropFunctions.CreateFile("data.txt",
FileInteropFunctions.GENERIC_WRITE,
0,
IntPtr.Zero,
FileInteropFunctions.CREATE_ALWAYS,
0,
0);
if(hFile.ToInt64( ) > 0)
{
// Write to the file using managed code.
// Wrap our file handle in a safe handle wrapper object.
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 ...