11.19. Opening a File Stream with just aFile Handle
Problem
When interoperating with unmanaged code, you encounter a situation where you are provided a file handle and no other information. This file handle must be used to open its corresponding file.
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 pass it to the
WriteToFileHandle managed method for writing data,
then flush and close the unmanaged file handle. This setup is
illustrated in the following
code:
public void UsingAnUnmanagedFileHandle( )
{
IntPtr hFile = IntPtr.Zero;
// create a file using unmanaged code
hFile = (IntPtr)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
WriteToFileHandle(hFile);
// close the file
FileInteropFunctions.CloseHandle(hFile);
// remove the file
File.Delete("data.txt");
}
}In order to write to the file handle, we wrap it in a
FileStream, passing the file handle as the first
parameter. Once we have the file stream, we use the capabilities of
the FileStream to write to the file handle by
getting the bytes from a string in ASCII encoding format and calling
Write on the file stream, as shown
here:
public static void WriteToFileHandle(IntPtr hFile) { // Open a FileStream object ...