O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required