Skip to Content
C# Cookbook
book

C# Cookbook

by Stephen Teilhet, Jay Hilyard
January 2004
Beginner to intermediate
864 pages
22h 18m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook

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 ...
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.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Joe Mayo
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
ASP.NET Cookbook

ASP.NET Cookbook

Michael A Kittel, Geoffrey T. LeBlond

Publisher Resources

ISBN: 0596003390Supplemental ContentCatalog PageErrata