
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Opening a File Stream with Just a File Handle
|
725
bytes from a string in ASCII-encoding format and call Write on the file stream, as
shown here:
byte[] bytes = Encoding.ASCII.GetBytes(line);
fileStream.Write(bytes,0,bytes.Length);
In order to perform the unmanaged functions of creating, flushing, and closing the
file handle, we have wrapped the unmanaged Win32 API functions for these func-
tions in the
FileInteropFunctions class shown in Example 12-9. The DllImport
attribute says that these functions are being used from kernel32.dll and the
SetLastError attribute is set to true, so that we can see if anything went wrong. A
few of the
#defines used with file creation have been brought over from unmanaged
code for readability.
Discussion
You can open a file using one of the overloaded constructors of the FileStream class
and passing a file handle into it. The
FileStream constructors in Version 2.0 of the
.NET Framework have been enhanced to accept a
Microsoft.Win32.SafeHandles.
SafeFileHandle
object instead of an IntPtr for the file handle. The SafeFileHandle
Example 12-9. FileInteropFunctions class
class FileInteropFunctions
{
public const uint GENERIC_READ = (0x80000000);
public const uint GENERIC_WRITE = (0x40000000);
public const uint GENERIC_EXECUTE = (0x20000000);
public const uint GENERIC_ALL ...