SafeFileHandle Class
.NET Framework 2.0
Note: This class is new in the .NET Framework version 2.0.
Represents a wrapper class for a file handle. This class cannot be inherited.
Namespace: Microsoft.Win32.SafeHandles
Assembly: mscorlib (in mscorlib.dll)
Assembly: mscorlib (in mscorlib.dll)
This class is derived from SafeHandleZeroOrMinusOneIsInvalid. A value of 0 or -1 is an invalid file handle.
The following code example demonstrates how to open a file using the SafeFileHandle class and the unmanaged CreateFile function.
using System; using Microsoft.Win32.SafeHandles; using System.Runtime.InteropServices; using System.ComponentModel; class SafeHandlesExample { static void Main() { try { UnmanagedFileLoader loader = new UnmanagedFileLoader("example.xml"); } catch (Exception e) { Console.WriteLine(e); } Console.ReadLine(); } } class UnmanagedFileLoader { public const short FILE_ATTRIBUTE_NORMAL = 0x80; public const short INVALID_HANDLE_VALUE = -1; public const uint GENERIC_READ = 0x80000000; public const uint GENERIC_WRITE = 0x40000000; public const uint CREATE_NEW = 1; public const uint CREATE_ALWAYS = 2; public const uint OPEN_EXISTING = 3; // Use interop to call the CreateFile function. // For more information about CreateFile, // see the unmanaged MSDN reference library. [DllImport("kernel32.dll", SetLastError = true)] static extern SafeFileHandle CreateFile(string lpFileName, uint dwDesiredAccess, uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition, uint dwFlagsAndAttributes, IntPtr hTemplateFile); private SafeFileHandle handleValue = null; public UnmanagedFileLoader(string Path) { Load(Path); } public void Load(string Path) { if (Path == null && Path.Length == 0) { throw new ArgumentNullException("Path"); } // Try to open the file. handleValue = CreateFile(Path, GENERIC_WRITE, 0, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero); // If the handle is invalid, // get the last Win32 error // and throw a Win32Exception. if (handleValue.IsInvalid) { Marshal.ThrowExceptionForHR(Marshal.GetLastWin32Error()); } } public SafeFileHandle Handle { get { // If the handle is valid, // return it. if (!handleValue.IsInvalid) { return handleValue; } else { return null; } } } }
System.Object
System.Runtime.ConstrainedExecution.CriticalFinalizerObject
System.Runtime.InteropServices.SafeHandle
Microsoft.Win32.SafeHandles.SafeHandleZeroOrMinusOneIsInvalid
Microsoft.Win32.SafeHandles.SafeFileHandle
System.Runtime.ConstrainedExecution.CriticalFinalizerObject
System.Runtime.InteropServices.SafeHandle
Microsoft.Win32.SafeHandles.SafeHandleZeroOrMinusOneIsInvalid
Microsoft.Win32.SafeHandles.SafeFileHandle
Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see System Requirements.