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
상속
특성

예제

다음 코드 예제에서는 클래스 및 관리 CreateFile 되지 않는 함수를 SafeFileHandle 사용하여 파일을 여는 방법을 보여 줍니다.

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 인터페이스입니다. 형식을 사용 하 여 마쳤으면 직접 또는 간접적으로의 삭제 해야 있습니다. 직접 형식의 dispose 호출 해당 Dispose 의 메서드를 try/catch 블록입니다. 삭제 하지 직접, 언어 구문 같은 사용 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)

적용 대상

추가 정보