Object.Finalize Metodo

Definizione

Consente a un oggetto di effettuare un tentativo di liberare risorse ed eseguire altre operazioni di pulizia prima che venga recuperato da Garbage Collection.

!Object ()
~Object ();
abstract member Finalize : unit -> unit
override this.Finalize : unit -> unit
Finalize ()

Esempio

Nell'esempio seguente viene verificato che il metodo viene chiamato quando viene eliminato un oggetto che esegue l'override Finalize Finalize . Si noti che, in un'applicazione di produzione, il Finalize metodo verrà sottoposto a override per rilasciare risorse non gestite mantenute dall'oggetto. Si noti anche che l'esempio C# fornisce un distruttore anziché eseguire l'override del Finalize metodo.

using System;
using System.Diagnostics;

public class ExampleClass
{
   Stopwatch sw;

   public ExampleClass()
   {
      sw = Stopwatch.StartNew();
      Console.WriteLine("Instantiated object");
   }

   public void ShowDuration()
   {
      Console.WriteLine("This instance of {0} has been in existence for {1}",
                        this, sw.Elapsed);
   }

   ~ExampleClass()
   {
      Console.WriteLine("Finalizing object");
      sw.Stop();
      Console.WriteLine("This instance of {0} has been in existence for {1}",
                        this, sw.Elapsed);
   }
}

public class Demo
{
   public static void Main()
   {
      ExampleClass ex = new ExampleClass();
      ex.ShowDuration();
   }
}
// The example displays output like the following:
//    Instantiated object
//    This instance of ExampleClass has been in existence for 00:00:00.0011060
//    Finalizing object
//    This instance of ExampleClass has been in existence for 00:00:00.0036294
open System.Diagnostics

type ExampleClass() =
    let sw = Stopwatch.StartNew()
    do 
        printfn "Instantiated object"

    member this.ShowDuration() =
        printfn $"This instance of {this} has been in existence for {sw.Elapsed}"

    override this.Finalize() =
        printfn "Finalizing object"
        sw.Stop()
        printfn $"This instance of {this} has been in existence for {sw.Elapsed}"

let ex = ExampleClass()
ex.ShowDuration()
// The example displays output like the following:
//    Instantiated object
//    This instance of ExampleClass has been in existence for 00:00:00.0011060
//    Finalizing object
//    This instance of ExampleClass has been in existence for 00:00:00.0036294
Imports System.Diagnostics

Public Class ExampleClass
   Dim sw As StopWatch
   
   Public Sub New()
      sw = Stopwatch.StartNew()
      Console.WriteLine("Instantiated object")
   End Sub 

   Public Sub ShowDuration()
      Console.WriteLine("This instance of {0} has been in existence for {1}",
                        Me, sw.Elapsed)
   End Sub
   
   Protected Overrides Sub Finalize()
      Console.WriteLine("Finalizing object")
      sw.Stop()
      Console.WriteLine("This instance of {0} has been in existence for {1}",
                        Me, sw.Elapsed)
   End Sub
End Class

Module Demo
   Public Sub Main()
      Dim ex As New ExampleClass()
      ex.ShowDuration()
   End Sub
End Module
' The example displays output like the following:
'    Instantiated object
'    This instance of ExampleClass has been in existence for 00:00:00.0011060
'    Finalizing object
'    This instance of ExampleClass has been in existence for 00:00:00.0036294

Per un esempio aggiuntivo che esegue l'override del Finalize metodo, vedere il GC.SuppressFinalize metodo .

Commenti

Il Finalize metodo viene usato per eseguire operazioni di pulizia sulle risorse non gestite mantenute dall'oggetto corrente prima che l'oggetto venga distrutto. Il metodo è protetto e pertanto è accessibile solo tramite questa classe o tramite una classe derivata.

Contenuto della sezione:

Funzionamento della finalizzazione

La Object classe non fornisce alcuna implementazione per il Finalize metodo e il Garbage Collector non contrassegna i tipi derivati dalla Object finalizzazione a meno che non eseseguono l'override del Finalize metodo.

Se un tipo esegue l'override del Finalize metodo, Garbage Collector aggiunge una voce per ogni istanza del tipo a una struttura interna denominata coda di finalizzazione. La coda di finalizzazione contiene voci per tutti gli oggetti nell'heap gestito il cui codice di finalizzazione deve essere eseguito prima che Garbage Collector possa recuperare la memoria. Garbage Collector chiama quindi automaticamente il Finalize metodo in base alle condizioni seguenti:

  • Dopo aver rilevato che un oggetto non è accessibile, a meno che l'oggetto non sia stato escluso dalla finalizzazione da una chiamata al GC.SuppressFinalize metodo.

  • In .NET Framework solo, durante l'arresto di un dominio applicazione, a meno che l'oggetto non sia escluso dalla finalizzazione. Durante l'arresto, anche gli oggetti che sono ancora accessibili vengono finalizzati.

Finalize viene chiamato automaticamente una sola volta in una determinata istanza, a meno che l'oggetto non venga nuovamente registrato usando un meccanismo come GC.ReRegisterForFinalize e il GC.SuppressFinalize metodo non è stato chiamato successivamente.

Finalize le operazioni presentano le limitazioni seguenti:

  • L'ora esatta in cui il finalizzatore viene eseguito non è definito. Per garantire il rilascio deterministico delle risorse per le istanze della classe, implementare un Close metodo o fornire un'implementazione IDisposable.Dispose .

  • I finalizzatori di due oggetti non sono garantiti per l'esecuzione in un ordine specifico, anche se un oggetto fa riferimento all'altro. Ovvero, se Object A ha un riferimento a Object B e entrambi hanno finalizzatori, Object B potrebbe essere già stato finalizzato quando viene avviato il finalizzatore dell'oggetto A.

  • Il thread in cui viene eseguito il finalizzatore non è specificato.

Il Finalize metodo potrebbe non essere eseguito al completamento o potrebbe non essere eseguito in tutte le circostanze eccezionali seguenti:

  • Se un altro finalizzatore blocca in modo indefinito (entra in un ciclo infinito, tenta di ottenere un blocco che non può mai ottenere e così via). Poiché il runtime tenta di eseguire finalizzatori per il completamento, altri finalizzatori potrebbero non essere chiamati se un finalizzatore blocca indefinito.

  • Se il processo termina senza concedere al runtime la possibilità di pulire. In questo caso, la prima notifica del runtime di terminazione del processo è una notifica DLL_PROCESS_DETACH.

Il runtime continua a finalizzare gli oggetti durante l'arresto solo mentre il numero di oggetti finalizzabili continua a diminuire.

Se Finalize o un override di Finalize genera un'eccezione e il runtime non è ospitato da un'applicazione che esegue l'override dei criteri predefiniti, il runtime termina il processo e non vengono eseguiti blocchi o finalizzatori attivi/try``finally. Questo comportamento garantisce l'integrità del processo se il finalizzatore non può liberare o distruggere le risorse.

Override del metodo Finalize

È consigliabile eseguire l'override Finalize per una classe che usa risorse non gestite, ad esempio handle di file o connessioni di database che devono essere rilasciate quando l'oggetto gestito che li usa viene rimosso durante la Garbage Collection. Non è consigliabile implementare un Finalize metodo per gli oggetti gestiti perché il Garbage Collector rilascia automaticamente le risorse gestite.

Importante

Se è disponibile un oggetto che esegue il wrapping della risorsa non gestita, l'alternativa consigliata consiste nell'implementare il modello di eliminazione con un SafeHandle handle sicuro e non eseguire l'override Finalizedi . Per altre informazioni, vedere La sezione alternativa SafeHandle .

Il Object.Finalize metodo non esegue nulla per impostazione predefinita, ma è consigliabile eseguire l'override solo se necessario e solo per rilasciare Finalize risorse non gestite. Il recupero della memoria tende a richiedere molto più tempo se viene eseguita un'operazione di finalizzazione, perché richiede almeno due garbage collection. Inoltre, è necessario eseguire l'override del Finalize metodo solo per i tipi di riferimento. Common Language Runtime finalizza solo i tipi di riferimento. Ignora gli finalizzatori sui tipi di valore.

L'ambito Object.Finalize del metodo è protected. È consigliabile mantenere questo ambito limitato quando si esegue l'override del metodo nella classe. Mantenendo protetto un Finalize metodo, si impedisce agli utenti dell'applicazione di chiamare direttamente il metodo di Finalize un oggetto.

Ogni implementazione di Finalize in un tipo derivato deve chiamare l'implementazione del tipo di base di Finalize. Si tratta dell'unico caso in cui il codice dell'applicazione è autorizzato a chiamare Finalize. Il metodo di Finalize un oggetto non deve chiamare un metodo su oggetti diversi da quello della classe base. Questo è dovuto al fatto che gli altri oggetti chiamati possono essere raccolti contemporaneamente all'oggetto chiamante, ad esempio nel caso di un arresto di Common Language Runtime.

Nota

Il compilatore C# non consente di eseguire l'override del Finalize metodo. Specificare invece un finalizzatore implementando un distruttore per la classe. Un distruttore C# chiama automaticamente il distruttore della classe base.

Visual C++ fornisce anche la propria sintassi per implementare il Finalize metodo. Per altre informazioni, vedere la sezione "Distruttori e finalizzatori" di Procedura: Definire e utilizzare classi e Struct (C++/CLI).

Poiché Garbage Collection non è deterministico, non si conosce esattamente quando il Garbage Collector esegue la finalizzazione. Per rilasciare immediatamente le risorse, è anche possibile scegliere di implementare il modello di eliminazione e l'interfaccia IDisposable . L'implementazione IDisposable.Dispose può essere chiamata dai consumer della classe per liberare risorse non gestite e è possibile usare il Finalize metodo per liberare risorse non gestite nel caso in cui il Dispose metodo non venga chiamato.

Finalize può eseguire quasi qualsiasi azione, inclusa la riattivazione di un oggetto (ovvero rendere nuovamente accessibile l'oggetto) dopo la pulizia durante la Garbage Collection. Tuttavia, l'oggetto può essere risorgere una sola volta; Finalize non può essere chiamato sugli oggetti rerieseretti durante la Garbage Collection.

Alternativa SafeHandle

La creazione di finalizzatori affidabili è spesso difficile, perché non è possibile effettuare ipotesi sullo stato dell'applicazione e perché le eccezioni di sistema non gestite, ad esempio OutOfMemoryException e StackOverflowException terminano il finalizzatore. Anziché implementare un finalizzatore per la classe per rilasciare risorse non gestite, è possibile usare un oggetto derivato dalla System.Runtime.InteropServices.SafeHandle classe per eseguire il wrapping delle risorse non gestite e quindi implementare il modello di eliminazione senza un finalizzatore. La .NET Framework fornisce le classi seguenti nello Microsoft.Win32 spazio dei nomi derivato da System.Runtime.InteropServices.SafeHandle:

Nell'esempio seguente viene usato il modello dispose con handle sicuri anziché eseguire l'override del Finalize metodo. Definisce una FileAssociation classe che esegue il wrapping delle informazioni del Registro di sistema sull'applicazione che gestisce i file con un'estensione di file specifica. I due handle del Registro di sistema restituiti come out parametri da Windows le chiamate di funzione RegOpenKeyEx vengono passate al SafeRegistryHandle costruttore. Il metodo protetto Dispose del tipo chiama quindi il SafeRegistryHandle.Dispose metodo per liberare questi due handle.

using Microsoft.Win32.SafeHandles;
using System;
using System.ComponentModel;
using System.IO;
using System.Runtime.InteropServices;

public class FileAssociationInfo : IDisposable
{
   // Private variables.
   private String ext;
   private String openCmd;
   private String args;
   private SafeRegistryHandle hExtHandle, hAppIdHandle;

   // Windows API calls.
   [DllImport("advapi32.dll", CharSet= CharSet.Auto, SetLastError=true)]
   private static extern int RegOpenKeyEx(IntPtr hKey,
                  String lpSubKey, int ulOptions, int samDesired,
                  out IntPtr phkResult);
   [DllImport("advapi32.dll", CharSet= CharSet.Unicode, EntryPoint = "RegQueryValueExW",
              SetLastError=true)]
   private static extern int RegQueryValueEx(IntPtr hKey,
                  string lpValueName, int lpReserved, out uint lpType,
                  string lpData, ref uint lpcbData);
   [DllImport("advapi32.dll", SetLastError = true)]
   private static extern int RegSetValueEx(IntPtr hKey, [MarshalAs(UnmanagedType.LPStr)] string lpValueName,
                  int Reserved, uint dwType, [MarshalAs(UnmanagedType.LPStr)] string lpData,
                  int cpData);
   [DllImport("advapi32.dll", SetLastError=true)]
   private static extern int RegCloseKey(UIntPtr hKey);

   // Windows API constants.
   private const int HKEY_CLASSES_ROOT = unchecked((int) 0x80000000);
   private const int ERROR_SUCCESS = 0;

    private const int KEY_QUERY_VALUE = 1;
    private const int KEY_SET_VALUE = 0x2;

   private const uint REG_SZ = 1;

   private const int MAX_PATH = 260;

   public FileAssociationInfo(String fileExtension)
   {
      int retVal = 0;
      uint lpType = 0;

      if (!fileExtension.StartsWith("."))
             fileExtension = "." + fileExtension;
      ext = fileExtension;

      IntPtr hExtension = IntPtr.Zero;
      // Get the file extension value.
      retVal = RegOpenKeyEx(new IntPtr(HKEY_CLASSES_ROOT), fileExtension, 0, KEY_QUERY_VALUE, out hExtension);
      if (retVal != ERROR_SUCCESS)
         throw new Win32Exception(retVal);
      // Instantiate the first SafeRegistryHandle.
      hExtHandle = new SafeRegistryHandle(hExtension, true);

      string appId = new string(' ', MAX_PATH);
      uint appIdLength = (uint) appId.Length;
      retVal = RegQueryValueEx(hExtHandle.DangerousGetHandle(), String.Empty, 0, out lpType, appId, ref appIdLength);
      if (retVal != ERROR_SUCCESS)
         throw new Win32Exception(retVal);
      // We no longer need the hExtension handle.
      hExtHandle.Dispose();

      // Determine the number of characters without the terminating null.
      appId = appId.Substring(0, (int) appIdLength / 2 - 1) + @"\shell\open\Command";

      // Open the application identifier key.
      string exeName = new string(' ', MAX_PATH);
      uint exeNameLength = (uint) exeName.Length;
      IntPtr hAppId;
      retVal = RegOpenKeyEx(new IntPtr(HKEY_CLASSES_ROOT), appId, 0, KEY_QUERY_VALUE | KEY_SET_VALUE,
                            out hAppId);
       if (retVal != ERROR_SUCCESS)
         throw new Win32Exception(retVal);

      // Instantiate the second SafeRegistryHandle.
      hAppIdHandle = new SafeRegistryHandle(hAppId, true);

      // Get the executable name for this file type.
      string exePath = new string(' ', MAX_PATH);
      uint exePathLength = (uint) exePath.Length;
      retVal = RegQueryValueEx(hAppIdHandle.DangerousGetHandle(), String.Empty, 0, out lpType, exePath, ref exePathLength);
      if (retVal != ERROR_SUCCESS)
         throw new Win32Exception(retVal);

      // Determine the number of characters without the terminating null.
      exePath = exePath.Substring(0, (int) exePathLength / 2 - 1);
      // Remove any environment strings.
      exePath = Environment.ExpandEnvironmentVariables(exePath);

      int position = exePath.IndexOf('%');
      if (position >= 0) {
         args = exePath.Substring(position);
         // Remove command line parameters ('%0', etc.).
         exePath = exePath.Substring(0, position).Trim();
      }
      openCmd = exePath;
   }

   public String Extension
   { get { return ext; } }

   public String Open
   { get { return openCmd; }
     set {
        if (hAppIdHandle.IsInvalid | hAppIdHandle.IsClosed)
           throw new InvalidOperationException("Cannot write to registry key.");
        if (! File.Exists(value)) {
           string message = String.Format("'{0}' does not exist", value);
           throw new FileNotFoundException(message);
        }
        string cmd = value + " %1";
        int retVal = RegSetValueEx(hAppIdHandle.DangerousGetHandle(), String.Empty, 0,
                                   REG_SZ, value, value.Length + 1);
        if (retVal != ERROR_SUCCESS)
           throw new Win32Exception(retVal);
     } }

   public void Dispose()
   {
      Dispose(disposing: true);
      GC.SuppressFinalize(this);
   }

   protected void Dispose(bool disposing)
   {
      // Ordinarily, we release unmanaged resources here;
      // but all are wrapped by safe handles.

      // Release disposable objects.
      if (disposing) {
         if (hExtHandle != null) hExtHandle.Dispose();
         if (hAppIdHandle != null) hAppIdHandle.Dispose();
      }
   }
}
open Microsoft.Win32.SafeHandles
open System
open System.ComponentModel
open System.IO
open System.Runtime.InteropServices

// Windows API constants.
let HKEY_CLASSES_ROOT = 0x80000000
let ERROR_SUCCESS = 0
let KEY_QUERY_VALUE = 1
let KEY_SET_VALUE = 0x2
let REG_SZ = 1u
let MAX_PATH = 260

// Windows API calls.
[<DllImport("advapi32.dll", CharSet= CharSet.Auto, SetLastError=true)>]
extern int RegOpenKeyEx(nativeint hKey, string lpSubKey, int ulOptions, int samDesired, nativeint& phkResult)
[<DllImport("advapi32.dll", CharSet= CharSet.Unicode, EntryPoint = "RegQueryValueExW", SetLastError=true)>]
extern int RegQueryValueEx(nativeint hKey, string lpValueName, int lpReserved, uint& lpType, string lpData, uint& lpcbData)
[<DllImport("advapi32.dll", SetLastError = true)>]
extern int RegSetValueEx(nativeint hKey, [<MarshalAs(UnmanagedType.LPStr)>] string lpValueName, int Reserved, uint dwType, [<MarshalAs(UnmanagedType.LPStr)>] string lpData, int cpData)
[<DllImport("advapi32.dll", SetLastError=true)>]
extern int RegCloseKey(unativeint hKey)

type FileAssociationInfo(fileExtension: string) =
    // Private values.
    let ext =
        if fileExtension.StartsWith "." |> not then
            "." + fileExtension
        else
            fileExtension
    let mutable args = ""
    let mutable hAppIdHandle = Unchecked.defaultof<SafeRegistryHandle>
    let mutable hExtHandle = Unchecked.defaultof<SafeRegistryHandle>
    let openCmd = 
        let mutable lpType = 0u
        let mutable hExtension = 0n
        // Get the file extension value.
        let retVal = RegOpenKeyEx(nativeint HKEY_CLASSES_ROOT, fileExtension, 0, KEY_QUERY_VALUE, &hExtension)
        if retVal <> ERROR_SUCCESS then
            raise (Win32Exception retVal)
        // Instantiate the first SafeRegistryHandle.
        hExtHandle <- new SafeRegistryHandle(hExtension, true)

        let appId = String(' ', MAX_PATH)
        let mutable appIdLength = uint appId.Length
        let retVal = RegQueryValueEx(hExtHandle.DangerousGetHandle(), String.Empty, 0, &lpType, appId, &appIdLength)
        if retVal <> ERROR_SUCCESS then
            raise (Win32Exception retVal)
        // We no longer need the hExtension handle.
        hExtHandle.Dispose()

        // Determine the number of characters without the terminating null.
        let appId = appId.Substring(0, int appIdLength / 2 - 1) + @"\shell\open\Command"

        // Open the application identifier key.
        let exeName = String(' ', MAX_PATH)
        let exeNameLength = uint exeName.Length
        let mutable hAppId = 0n
        let retVal = RegOpenKeyEx(nativeint HKEY_CLASSES_ROOT, appId, 0, KEY_QUERY_VALUE ||| KEY_SET_VALUE, &hAppId)
        if retVal <> ERROR_SUCCESS then
            raise (Win32Exception retVal)

        // Instantiate the second SafeRegistryHandle.
        hAppIdHandle <- new SafeRegistryHandle(hAppId, true)

        // Get the executable name for this file type.
        let exePath = String(' ', MAX_PATH)
        let mutable exePathLength = uint exePath.Length
        let retVal = RegQueryValueEx(hAppIdHandle.DangerousGetHandle(), String.Empty, 0, &lpType, exePath, &exePathLength)
        if retVal <> ERROR_SUCCESS then
            raise (Win32Exception retVal)

        // Determine the number of characters without the terminating null.
        let exePath = 
            exePath.Substring(0, int exePathLength / 2 - 1)
            // Remove any environment strings.
            |> Environment.ExpandEnvironmentVariables

        let position = exePath.IndexOf '%'
        if position >= 0 then
            args <- exePath.Substring position
            // Remove command line parameters ('%0', etc.).
            exePath.Substring(0, position).Trim()
        else
            exePath

    member _.Extension =
        ext

    member _.Open
        with get () = openCmd
        and set (value) =
            if hAppIdHandle.IsInvalid || hAppIdHandle.IsClosed then
                raise (InvalidOperationException "Cannot write to registry key.")
            if not (File.Exists value) then
                raise (FileNotFoundException $"'{value}' does not exist")
            
            let cmd = value + " %1"
            let retVal = RegSetValueEx(hAppIdHandle.DangerousGetHandle(), String.Empty, 0, REG_SZ, value, value.Length + 1)
            if retVal <> ERROR_SUCCESS then
                raise (Win32Exception retVal)

    member this.Dispose() =
        this.Dispose true
        GC.SuppressFinalize this

    member _.Dispose(disposing) =
        // Ordinarily, we release unmanaged resources here
        // but all are wrapped by safe handles.

        // Release disposable objects.
        if disposing then
           if hExtHandle <> null then hExtHandle.Dispose()
           if hAppIdHandle <> null then hAppIdHandle.Dispose()

    interface IDisposable with
        member this.Dispose() =
            this.Dispose()
Imports Microsoft.Win32.SafeHandles
Imports System.ComponentModel
Imports System.IO
Imports System.Runtime.InteropServices
Imports System.Text

Public Class FileAssociationInfo : Implements IDisposable
   ' Private variables.
   Private ext As String
   Private openCmd As String
   Private args As String
   Private hExtHandle, hAppIdHandle As SafeRegistryHandle

   ' Windows API calls.
   Private Declare Unicode Function RegOpenKeyEx Lib"advapi32.dll" _
                   Alias "RegOpenKeyExW" (hKey As IntPtr, lpSubKey As String, _
                   ulOptions As Integer, samDesired As Integer, _
                   ByRef phkResult As IntPtr) As Integer
   Private Declare Unicode Function RegQueryValueEx Lib "advapi32.dll" _
                   Alias "RegQueryValueExW" (hKey As IntPtr, _
                   lpValueName As String, lpReserved As Integer, _
                   ByRef lpType As UInteger, lpData As String, _
                   ByRef lpcbData As UInteger) As Integer
   Private Declare Function RegSetValueEx Lib "advapi32.dll" _
                  (hKey As IntPtr, _
                  <MarshalAs(UnmanagedType.LPStr)> lpValueName As String, _
                  reserved As Integer, dwType As UInteger, _
                  <MarshalAs(UnmanagedType.LPStr)> lpData As String, _
                  cpData As Integer) As Integer
   Private Declare Function RegCloseKey Lib "advapi32.dll" _
                  (hKey As IntPtr) As Integer

   ' Windows API constants.
   Private Const HKEY_CLASSES_ROOT As Integer = &h80000000
   Private Const ERROR_SUCCESS As Integer = 0

   Private Const KEY_QUERY_VALUE As Integer = 1
   Private Const KEY_SET_VALUE As Integer = &h2

   Private REG_SZ As UInteger = 1

   Private Const MAX_PATH As Integer  = 260

   Public Sub New(fileExtension As String)
      Dim retVal As Integer = 0
      Dim lpType As UInteger = 0

      If Not fileExtension.StartsWith(".") Then
         fileExtension = "." + fileExtension
      End If
      ext = fileExtension

      Dim hExtension As IntPtr = IntPtr.Zero
      ' Get the file extension value.
      retVal = RegOpenKeyEx(New IntPtr(HKEY_CLASSES_ROOT), fileExtension, 0,
                            KEY_QUERY_VALUE, hExtension)
      if retVal <> ERROR_SUCCESS Then
         Throw New Win32Exception(retVal)
      End If
      ' Instantiate the first SafeRegistryHandle.
      hExtHandle = New SafeRegistryHandle(hExtension, True)

      Dim appId As New String(" "c, MAX_PATH)
      Dim appIdLength As UInteger = CUInt(appId.Length)
      retVal = RegQueryValueEx(hExtHandle.DangerousGetHandle(), String.Empty, _
                               0, lpType, appId, appIdLength)
      if retVal <> ERROR_SUCCESS Then
         Throw New Win32Exception(retVal)
      End If
      ' We no longer need the hExtension handle.
      hExtHandle.Dispose()

      ' Determine the number of characters without the terminating null.
      appId = appId.Substring(0, CInt(appIdLength) \ 2 - 1) + "\shell\open\Command"

      ' Open the application identifier key.
      Dim exeName As New string(" "c, MAX_PATH)
      Dim exeNameLength As UInteger = CUInt(exeName.Length)
      Dim hAppId As IntPtr
      retVal = RegOpenKeyEx(New IntPtr(HKEY_CLASSES_ROOT), appId, 0,
                            KEY_QUERY_VALUE Or KEY_SET_VALUE, hAppId)
      If retVal <> ERROR_SUCCESS Then
         Throw New Win32Exception(retVal)
      End If

      ' Instantiate the second SafeRegistryHandle.
      hAppIdHandle = New SafeRegistryHandle(hAppId, True)

      ' Get the executable name for this file type.
      Dim exePath As New string(" "c, MAX_PATH)
      Dim exePathLength As UInteger = CUInt(exePath.Length)
      retVal = RegQueryValueEx(hAppIdHandle.DangerousGetHandle(), _
                               String.Empty, 0, lpType, exePath, exePathLength)
      If retVal <> ERROR_SUCCESS Then
         Throw New Win32Exception(retVal)
      End If
      ' Determine the number of characters without the terminating null.
      exePath = exePath.Substring(0, CInt(exePathLength) \ 2 - 1)

      exePath = Environment.ExpandEnvironmentVariables(exePath)
      Dim position As Integer = exePath.IndexOf("%"c)
      If position >= 0 Then
         args = exePath.Substring(position)
         ' Remove command line parameters ('%0', etc.).
         exePath = exePath.Substring(0, position).Trim()
      End If
      openCmd = exePath
   End Sub

   Public ReadOnly Property Extension As String
      Get
         Return ext
      End Get
   End Property

   Public Property Open As String
      Get
         Return openCmd
      End Get
      Set
        If hAppIdHandle.IsInvalid Or hAppIdHandle.IsClosed Then
           Throw New InvalidOperationException("Cannot write to registry key.")
        End If
        If Not File.Exists(value) Then
           Dim message As String = String.Format("'{0}' does not exist", value)
           Throw New FileNotFoundException(message)
        End If
        Dim cmd As String = value + " %1"
        Dim retVal As Integer = RegSetValueEx(hAppIdHandle.DangerousGetHandle(), String.Empty, 0,
                                              REG_SZ, value, value.Length + 1)
        If retVal <> ERROR_SUCCESS Then
           Throw New Win32Exception(retVal)
        End If
      End Set
   End Property

   Public Sub Dispose() _
      Implements IDisposable.Dispose
      Dispose(disposing:=True)
      GC.SuppressFinalize(Me)
   End Sub

   Protected Sub Dispose(disposing As Boolean)
      ' Ordinarily, we release unmanaged resources here
      ' but all are wrapped by safe handles.

      ' Release disposable objects.
      If disposing Then
         If hExtHandle IsNot Nothing Then hExtHandle.Dispose()
         If hAppIdHandle IsNot Nothing Then hAppIdHandle.Dispose()
      End If
   End Sub
End Class

Si applica a

Vedi anche