SafeFileHandle 類別

定義

代表檔案封裝類別。

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(nameof(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 (!handleValue.IsInvalid)
                return handleValue;
            
            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 的值即為無效的檔案帳柄。

Important

此類型會實作 IDisposable 介面。 當您完成使用這個物品後,應直接或間接地處理它。 若要直接處置類型,請在 Disposetry/ 區塊中呼叫其 catch 方法。 若要間接處置它,請使用語言建構,例如 using (C#) 或 Using (在 Visual Basic 中)。 如需詳細資訊,請參閱介面主題中的 <使用實作 IDisposable 的物件>一節。

建構函式

名稱 Description
SafeFileHandle()

建立一個檔案柄周圍的 。SafeFileHandle

SafeFileHandle(IntPtr, Boolean)

初始化 SafeFileHandle 類別的新執行個體。

欄位

名稱 Description
handle

指定要包裹的把手。

(繼承來源 SafeHandle)

屬性

名稱 Description
IsAsync

會得到一個值,用來判斷該句柄是否非同步。

IsClosed

會得到一個值,表示把柄是否已關閉。

(繼承來源 SafeHandle)
IsInvalid

會得到一個值,表示該句柄是否無效。

IsInvalid

會得到一個值,表示該句柄是否無效。

(繼承來源 SafeHandleZeroOrMinusOneIsInvalid)
Type

代表檔案封裝類別。

方法

名稱 Description
Close()

標記釋放與釋放資源的把手。

(繼承來源 SafeHandle)
CreateAnonymousPipe(SafeFileHandle, SafeFileHandle, Boolean, Boolean)

代表檔案封裝類別。

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()

當在衍生類別中覆寫時,會執行釋放 handle 所需的程式碼。

(繼承來源 SafeHandle)
SetHandle(IntPtr)

將 handle 設為指定的既存 handle。

(繼承來源 SafeHandle)
SetHandleAsInvalid()

標記一個不再使用的把手。

(繼承來源 SafeHandle)
ToString()

傳回表示目前 物件的字串。

(繼承來源 Object)

適用於

另請參閱