SafeFileHandle 클래스
정의
중요
일부 정보는 릴리스되기 전에 상당 부분 수정될 수 있는 시험판 제품과 관련이 있습니다. Microsoft는 여기에 제공된 정보에 대해 어떠한 명시적이거나 묵시적인 보증도 하지 않습니다.
파일 핸들의 래퍼 클래스를 나타냅니다.
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 사용하여 파일을 여는 방법을 보여 줍니다.
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을 구현하는 개체 사용" 섹션을 IDisposable 참조하세요.
생성자
| Name | Description |
|---|---|
| SafeFileHandle() |
파일 핸들 주변 SafeFileHandle 을 만듭니다. |
| SafeFileHandle(IntPtr, Boolean) |
SafeFileHandle 클래스의 새 인스턴스를 초기화합니다. |
필드
| Name | Description |
|---|---|
| handle |
래핑할 핸들을 지정합니다. (다음에서 상속됨 SafeHandle) |
속성
| Name | Description |
|---|---|
| IsAsync |
핸들이 비동기인지 여부를 결정하는 값을 가져옵니다. |
| IsClosed |
핸들이 닫혀 있는지 여부를 나타내는 값을 가져옵니다. (다음에서 상속됨 SafeHandle) |
| IsInvalid |
핸들이 잘못된지 여부를 나타내는 값을 가져옵니다. |
| IsInvalid |
핸들이 잘못된지 여부를 나타내는 값을 가져옵니다. (다음에서 상속됨 SafeHandleZeroOrMinusOneIsInvalid) |
| Type |
파일 핸들의 래퍼 클래스를 나타냅니다. |
메서드
| Name | 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() |
파생 클래스에서 재정의된 경우 핸들을 해제하는 데 필요한 코드를 실행합니다. (다음에서 상속됨 SafeHandle) |
| SetHandle(IntPtr) |
핸들을 지정된 기존 핸들로 설정합니다. (다음에서 상속됨 SafeHandle) |
| SetHandleAsInvalid() |
핸들을 더 이상 사용되지 않는 것으로 표시합니다. (다음에서 상속됨 SafeHandle) |
| ToString() |
현재 개체를 나타내는 문자열을 반환합니다. (다음에서 상속됨 Object) |