SafeFileHandle Classe
Definizione
Importante
Alcune informazioni sono relative alla release non definitiva del prodotto, che potrebbe subire modifiche significative prima della release definitiva. Microsoft non riconosce alcuna garanzia, espressa o implicita, in merito alle informazioni qui fornite.
Rappresenta una classe wrapper per un handle di 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
- Ereditarietà
- Ereditarietà
- Attributi
Esempio
Nell'esempio di codice seguente viene illustrato come aprire un file usando la SafeFileHandle classe e la funzione non gestita 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
Commenti
Questa classe è derivata da SafeHandleZeroOrMinusOneIsInvalid. Il valore 0 o -1 è un handle di file non valido.
Important
Questo tipo implementa l'interfaccia IDisposable . Al termine dell'uso del tipo, è necessario eliminarlo direttamente o indirettamente. Per eliminare direttamente il tipo, chiamare il Dispose relativo metodo in un try/catch blocco. Per eliminarlo indirettamente, usare un costrutto del linguaggio, ad using esempio (in C#) o Using (in Visual Basic). Per altre informazioni, vedere la sezione "Uso di un oggetto che implementa IDisposable" nell'argomento relativo all'interfaccia IDisposable .
Costruttori
| Nome | Descrizione |
|---|---|
| SafeFileHandle(IntPtr, Boolean) |
Inizializza una nuova istanza della classe SafeFileHandle. |
Campi
| Nome | Descrizione |
|---|---|
| handle |
Specifica l'handle di cui eseguire il wrapping. (Ereditato da SafeHandle) |
Proprietà
| Nome | Descrizione |
|---|---|
| IsClosed |
Ottiene un valore che indica se l'handle è chiuso. (Ereditato da SafeHandle) |
| IsInvalid |
Ottiene un valore che indica se l'handle non è valido. |
| IsInvalid |
Ottiene un valore che indica se l'handle non è valido. (Ereditato da SafeHandleZeroOrMinusOneIsInvalid) |
Metodi
| Nome | Descrizione |
|---|---|
| Close() |
Contrassegna l'handle per il rilascio e la liberazione delle risorse. (Ereditato da SafeHandle) |
| DangerousAddRef(Boolean) |
Incrementa manualmente il contatore di riferimento nelle SafeHandle istanze di . (Ereditato da SafeHandle) |
| DangerousGetHandle() |
Restituisce il valore del handle campo. (Ereditato da SafeHandle) |
| DangerousRelease() |
Decrementa manualmente il contatore di riferimento in un'istanza SafeHandle di . (Ereditato da SafeHandle) |
| Dispose() |
Rilascia tutte le risorse usate dalla SafeHandle classe . (Ereditato da SafeHandle) |
| Dispose(Boolean) |
Rilascia le risorse non gestite usate dalla SafeHandle classe specificando se eseguire un'operazione dispose normale. (Ereditato da SafeHandle) |
| Equals(Object) |
Determina se l'oggetto specificato è uguale all'oggetto corrente. (Ereditato da Object) |
| GetHashCode() |
Funge da funzione hash predefinita. (Ereditato da Object) |
| GetType() |
Ottiene il Type dell'istanza corrente. (Ereditato da Object) |
| MemberwiseClone() |
Crea una copia superficiale del Objectcorrente. (Ereditato da Object) |
| ReleaseHandle() |
Quando sottoposto a override in una classe derivata, esegue il codice necessario per liberare l'handle. (Ereditato da SafeHandle) |
| SetHandle(IntPtr) |
Imposta l'handle sull'handle esistente specificato. (Ereditato da SafeHandle) |
| SetHandleAsInvalid() |
Contrassegna un handle come non più utilizzato. (Ereditato da SafeHandle) |
| ToString() |
Restituisce una stringa che rappresenta l'oggetto corrente. (Ereditato da Object) |