SafeFileHandle 类

定义

表示 file 句柄的包装类。

public ref class SafeFileHandle sealed : System::Runtime::InteropServices::SafeHandle
public ref class SafeFileHandle sealed : Microsoft::Win32::SafeHandles::SafeHandleZeroOrMinusOneIsInvalid
[System.Security.SecurityCritical]
public sealed class SafeFileHandle : System.Runtime.InteropServices.SafeHandle
public sealed class SafeFileHandle : Microsoft.Win32.SafeHandles.SafeHandleZeroOrMinusOneIsInvalid
[System.Security.SecurityCritical]
public sealed class SafeFileHandle : Microsoft.Win32.SafeHandles.SafeHandleZeroOrMinusOneIsInvalid
[<System.Security.SecurityCritical>]
type SafeFileHandle = class
    inherit SafeHandle
type SafeFileHandle = class
    inherit SafeHandleZeroOrMinusOneIsInvalid
[<System.Security.SecurityCritical>]
type SafeFileHandle = class
    inherit SafeHandleZeroOrMinusOneIsInvalid
Public NotInheritable Class SafeFileHandle
Inherits SafeHandle
Public NotInheritable Class SafeFileHandle
Inherits SafeHandleZeroOrMinusOneIsInvalid
继承
SafeFileHandle
继承
属性

示例

下面的代码示例演示如何使用 SafeFileHandle 类和非托管 CreateFile 函数打开文件。

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, CharSet=CharSet.Unicode)]
    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.GetHRForLastWin32Error());
        }
    }

    public SafeFileHandle Handle
    {
        get
        {
            // If the handle is valid,
            // return it.
            if (!handleValue.IsInvalid)
            {
                return handleValue;
            }
            else
            {
                return null;
            }
        }
    }
}
Imports Microsoft.Win32.SafeHandles
Imports System.Runtime.InteropServices
Imports System.ComponentModel



Module SafeHandlesExample

    Sub Main()
        Try

            Dim loader As New UnmanagedFileLoader("example.xml")


        Catch e As Exception
            Console.WriteLine(e)
        End Try
        Console.ReadLine()

    End Sub
End Module



Class UnmanagedFileLoader


    Public Const FILE_ATTRIBUTE_NORMAL As Short = &H80
    Public Const INVALID_HANDLE_VALUE As Short = -1
    Public Const GENERIC_READ As Long = &H80000000
    Public Const GENERIC_WRITE As UInteger = &H40000000
    Public Const CREATE_NEW As UInteger = 1
    Public Const CREATE_ALWAYS As UInteger = 2
    Public Const OPEN_EXISTING As UInteger = 3


    ' Use interop to call the CreateFile function.
    ' For more information about CreateFile,
    ' see the unmanaged MSDN reference library.
    <DllImport("kernel32.dll", SetLastError:=True, CharSet:=CharSet.Unicode)> _
    Private Shared Function CreateFile(ByVal lpFileName As String, ByVal dwDesiredAccess As System.UInt32, ByVal dwShareMode As System.UInt32, ByVal lpSecurityAttributes As IntPtr, ByVal dwCreationDisposition As System.UInt32, ByVal dwFlagsAndAttributes As System.UInt32, ByVal hTemplateFile As IntPtr) As Microsoft.Win32.SafeHandles.SafeFileHandle

    End Function


    Private handleValue As Microsoft.Win32.SafeHandles.SafeFileHandle = Nothing



    Public Sub New(ByVal Path As String)
        Load(Path)

    End Sub


    Public Sub Load(ByVal Path As String)
        If Path Is Nothing OrElse Path.Length = 0 Then
            Throw New ArgumentNullException("Path")
        End If

        ' 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 Then
            Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error())
        End If

    End Sub


    Public ReadOnly Property Handle() As Microsoft.Win32.SafeHandles.SafeFileHandle
        Get
            ' If the handle is valid,
            ' return it.
            If Not handleValue.IsInvalid Then
                Return handleValue
            Else
                Return Nothing
            End If
        End Get
    End Property
End Class

注解

此类是从 SafeHandleZeroOrMinusOneIsInvalid 派生的。 值 0 或 -1 是无效的文件句柄。

重要

此类型实现 IDisposable 接口。 在使用完类型后,您应直接或间接释放类型。 若要直接释放类型,请在 try/catch 块中调用其 Dispose 方法。 若要间接释放类型,请使用 using(在 C# 中)或 Using(在 Visual Basic 中)等语言构造。 有关详细信息,请参阅 IDisposable 接口主题中的“使用实现 IDisposable 的对象”一节。

构造函数

SafeFileHandle()

SafeFileHandle 文件句柄周围创建 。

SafeFileHandle(IntPtr, Boolean)

初始化 SafeFileHandle 类的新实例。

字段

handle

指定要包装的句柄。

(继承自 SafeHandle)

属性

IsAsync

获取一个值,该值确定句柄是否为异步。

IsClosed

获取一个值,该值指示句柄是否已关闭。

(继承自 SafeHandle)
IsInvalid

获取一个值,该值指示句柄是否无效。

IsInvalid

获取一个值,该值指示句柄是否无效。

(继承自 SafeHandleZeroOrMinusOneIsInvalid)

方法

Close()

标记句柄,以便释放资源。

(继承自 SafeHandle)
DangerousAddRef(Boolean)

手动递增 SafeHandle 实例中的引用计数器。

(继承自 SafeHandle)
DangerousGetHandle()

返回 handle 字段的值。

(继承自 SafeHandle)
DangerousRelease()

手动递减 SafeHandle 实例中的引用计数器。

(继承自 SafeHandle)
Dispose()

释放 SafeHandle 类使用的所有资源。

(继承自 SafeHandle)
Dispose(Boolean)

释放 SafeHandle 类所使用的非托管资源,指定是否执行常规释放操作。

(继承自 SafeHandle)
Equals(Object)

确定指定对象是否等于当前对象。

(继承自 Object)
GetHashCode()

作为默认哈希函数。

(继承自 Object)
GetType()

获取当前实例的 Type

(继承自 Object)
MemberwiseClone()

创建当前 Object 的浅表副本。

(继承自 Object)
ReleaseHandle()

在派生类中重写时,执行释放句柄所需的代码。

(继承自 SafeHandle)
SetHandle(IntPtr)

将句柄设置为预先存在的指定句柄。

(继承自 SafeHandle)
SetHandleAsInvalid()

将句柄标记为不再使用。

(继承自 SafeHandle)
ToString()

返回表示当前对象的字符串。

(继承自 Object)

适用于

另请参阅