Share via


PerformanceCounterCategory.CounterExists Método

Definición

Determina si un contador especificado está registrado en una categoría en particular.

Sobrecargas

CounterExists(String)

Determina si el contador especificado está registrado en esta categoría; esta información se indica mediante las propiedades CategoryName y MachineName.

CounterExists(String, String)

Determina si el contador especificado está registrado en la categoría especificada del equipo local.

CounterExists(String, String, String)

Determina si el contador especificado está registrado en la categoría especificada de un equipo remoto.

CounterExists(String)

Source:
PerformanceCounterCategory.cs
Source:
PerformanceCounterCategory.cs
Source:
PerformanceCounterCategory.cs

Determina si el contador especificado está registrado en esta categoría; esta información se indica mediante las propiedades CategoryName y MachineName.

public:
 bool CounterExists(System::String ^ counterName);
public bool CounterExists (string counterName);
member this.CounterExists : string -> bool
Public Function CounterExists (counterName As String) As Boolean

Parámetros

counterName
String

Nombre del contador de rendimiento que se va a buscar.

Devoluciones

Es true si el contador está registrado en la categoría especificada por las propiedades CategoryName y MachineName; de lo contrario, es false.

Excepciones

El valor de counterName es null.

No se ha establecido el valor de la propiedad CategoryName.

Se ha producido un error en la llamada a una API del sistema subyacente.

Código que se ejecuta sin privilegios administrativos para intentar leer un contador de rendimiento.

Ejemplos

En el ejemplo de código siguiente se determina si existe .PerformanceCounter Obtiene un nombre de categoría, un nombre de contador y un nombre de equipo de la línea de comandos, si se proporcionan. Crea un PerformanceCounterCategory objeto mediante el adecuado PerformanceCounterCategory. A continuación, usa el CounterExists(String) método para determinar si existe el especificado PerformanceCounter e informa al usuario.

public static void Main(string[] args)
{
    string categoryName = "";
    string counterName = "";
    string machineName = "";
    bool objectExists = false;
    PerformanceCounterCategory pcc;

    // Copy the supplied arguments into the local variables.
    try
    {
        categoryName = args[0];
        counterName = args[1];
        machineName = (args[2]=="."? "": args[2]);
    }
    catch(Exception ex)
    {
        // Ignore the exception from non-supplied arguments.
    }

    try
    {
        if (machineName.Length==0)
        {
            pcc = new PerformanceCounterCategory(categoryName);
        }
        else
        {
            pcc = new PerformanceCounterCategory(categoryName, machineName);
        }

        // Check whether the specified counter exists.
        // Use the per-instance overload of CounterExists.
        objectExists = pcc.CounterExists(counterName);
    }
    catch(Exception ex)
    {
        Console.WriteLine("Unable to check for the existence of " +
            "counter \"{0}\" in category \"{1}\" on "+
            (machineName.Length>0? "computer \"{2}\".": "this computer.")+ "\n" +
            ex.Message, counterName, categoryName, machineName);
        return;
    }

    // Tell the user whether the counter exists.
    Console.WriteLine("Counter \"{0}\" " + (objectExists? "exists": "does not exist") +
        " in category \"{1}\" on " + (machineName.Length>0? "computer \"{2}\".": "this computer."),
        counterName, pcc.CategoryName, pcc.MachineName);
}
Sub Main(ByVal args() As String)
    Dim categoryName As String = ""
    Dim counterName As String = ""
    Dim machineName As String = ""
    Dim objectExists As Boolean = False
    Dim pcc As PerformanceCounterCategory

    ' Copy the supplied arguments into the local variables.
    Try
        categoryName = args(0)
        counterName = args(1)
        machineName = IIf(args(2) = ".", "", args(2))
    Catch ex As Exception
        ' Ignore the exception from non-supplied arguments.
    End Try

    Try
        If machineName.Length = 0 Then
            pcc = New PerformanceCounterCategory(categoryName)
        Else
            pcc = New PerformanceCounterCategory(categoryName, machineName)
        End If

        ' Check whether the specified counter exists.
        ' Use the per-instance overload of CounterExists.
        objectExists = pcc.CounterExists(counterName)

    Catch ex As Exception
        Console.WriteLine("Unable to check for the existence of " & _
            "counter ""{0}"" in category ""{1}"" on " & _
            IIf(machineName.Length > 0, _
            "computer ""{2}"".", "this computer.") & vbCrLf & _
            ex.Message, counterName, categoryName, machineName)
        Return
    End Try

    ' Tell the user whether the counter exists.
    Console.WriteLine("Counter ""{0}"" " & _
        IIf(objectExists, "exists", "does not exist") & _
        " in category ""{1}"" on " & _
        IIf(machineName.Length > 0, _
            "computer ""{2}"".", "this computer."), _
        counterName, pcc.CategoryName, pcc.MachineName)
End Sub

Comentarios

Debe establecer la CategoryName propiedad antes de llamar a este método. De lo contrario, se inicia una excepción.

Si no ha establecido la MachineName propiedad , este método usa el equipo local (".").

Nota

Para leer contadores de rendimiento de una sesión de inicio de sesión no interactiva en Windows Vista y versiones posteriores, Windows XP Professional x64 Edition o Windows Server 2003, debe ser miembro del grupo Usuarios de Monitor de rendimiento o tener privilegios administrativos.

Para evitar tener que elevar los privilegios para acceder a los contadores de rendimiento en Windows Vista y versiones posteriores, agréguese al grupo usuarios de Monitor de rendimiento.

En Windows Vista y versiones posteriores, el Control de cuentas de usuario (UAC) determina los privilegios de un usuario. Si es miembro del grupo Administradores integrados, se le asignarán dos símbolos (tokens) de acceso en tiempo de ejecución: un símbolo (token) de acceso de usuario estándar y un símbolo (token) de acceso de administrador. De forma predeterminada, se le asignará el rol de usuario estándar. Para ejecutar el código que accede a los contadores de rendimiento, primero debe elevar los privilegios del usuario estándar al administrador. Para ello, inicie una aplicación haciendo clic con el botón derecho en el icono de la aplicación e indique que desea ejecutarla como administrador.

Consulte también

Se aplica a

CounterExists(String, String)

Source:
PerformanceCounterCategory.cs
Source:
PerformanceCounterCategory.cs
Source:
PerformanceCounterCategory.cs

Determina si el contador especificado está registrado en la categoría especificada del equipo local.

public:
 static bool CounterExists(System::String ^ counterName, System::String ^ categoryName);
public static bool CounterExists (string counterName, string categoryName);
static member CounterExists : string * string -> bool
Public Shared Function CounterExists (counterName As String, categoryName As String) As Boolean

Parámetros

counterName
String

Nombre del contador de rendimiento que se va a buscar.

categoryName
String

Nombre de la categoría de contador de rendimiento u objeto de rendimiento al que está asociado el contador de rendimiento especificado.

Devoluciones

Es true si el contador está registrado en la categoría especificada del equipo local; de lo contrario, es false.

Excepciones

El valor de categoryName es null.

o bien

El valor de counterName es null.

categoryName es una cadena vacía ("").

El nombre de categoría especificado no existe.

Se ha producido un error en la llamada a una API del sistema subyacente.

Código que se ejecuta sin privilegios administrativos para intentar leer un contador de rendimiento.

Ejemplos

En el ejemplo de código siguiente se determina si existe .PerformanceCounter Obtiene un nombre de categoría, un nombre de contador y un nombre de equipo de la línea de comandos, si se proporcionan. Usa las sobrecargas estáticas del CounterExists método para determinar si el nombre especificado PerformanceCounter existe en .PerformanceCounterCategory La sobrecarga se selecciona en función de si se proporciona un nombre de equipo.

public static void Main(string[] args)
{
    string categoryName = "";
    string counterName = "";
    string machineName = "";
    bool objectExists = false;

    // Copy the supplied arguments into the local variables.
    try
    {
        categoryName = args[0];
        counterName = args[1];
        machineName = args[2]=="."? "": args[2];
    }
    catch(Exception ex)
    {
        // Ignore the exception from non-supplied arguments.
    }

    try
    {
        // Check whether the specified counter exists.
        // Use the static forms of the CounterExists method.
        if (machineName.Length==0)
        {
            objectExists = PerformanceCounterCategory.CounterExists(counterName, categoryName);
        }
        else
        {
            objectExists = PerformanceCounterCategory.CounterExists(counterName, categoryName, machineName);
        }
    }
    catch(Exception ex)
    {
        Console.WriteLine("Unable to check for the existence of " +
            "counter \"{0}\" in category \"{1}\" on " +
            (machineName.Length>0? "computer \"{2}\".": "this computer.") + "\n" +
            ex.Message, counterName, categoryName, machineName);
        return;
    }

    // Tell the user whether the counter exists.
    Console.WriteLine("Counter \"{0}\" "+ (objectExists? "exists": "does not exist") +
        " in category \"{1}\" on " + (machineName.Length>0? "computer \"{2}\".": "this computer."),
        counterName, categoryName, machineName);
}
Sub Main(ByVal args() As String)
    Dim categoryName As String = ""
    Dim counterName As String = ""
    Dim machineName As String = ""
    Dim objectExists As Boolean = False

    ' Copy the supplied arguments into the local variables.
    Try
        categoryName = args(0)
        counterName = args(1)
        machineName = IIf(args(2) = ".", "", args(2))
    Catch ex As Exception
        ' Ignore the exception from non-supplied arguments.
    End Try

    Try
        ' Check whether the specified counter exists.
        ' Use the static forms of the CounterExists method.
        If machineName.Length = 0 Then
            objectExists = PerformanceCounterCategory.CounterExists( _
                counterName, categoryName)
        Else
            objectExists = PerformanceCounterCategory.CounterExists( _
                counterName, categoryName, machineName)
        End If

    Catch ex As Exception
        Console.WriteLine("Unable to check for the existence of " & _
            "counter ""{0}"" in category ""{1}"" on " & _
            IIf(machineName.Length > 0, _
            "computer ""{2}"".", "this computer.") & vbCrLf & _
            ex.Message, counterName, categoryName, machineName)
        Return
    End Try

    ' Tell the user whether the counter exists.
    Console.WriteLine("Counter ""{0}"" " & _
        IIf(objectExists, "exists", "does not exist") & _
        " in category ""{1}"" on " & _
        IIf(machineName.Length > 0, _
            "computer ""{2}"".", "this computer."), _
        counterName, categoryName, machineName)
End Sub

Comentarios

Nota

Para leer contadores de rendimiento de una sesión de inicio de sesión no interactiva en Windows Vista y versiones posteriores, Windows XP Professional x64 Edition o Windows Server 2003, debe ser miembro del grupo Usuarios de Monitor de rendimiento o tener privilegios administrativos.

Para evitar tener que elevar los privilegios para acceder a los contadores de rendimiento en Windows Vista y versiones posteriores, agréguese al grupo usuarios de Monitor de rendimiento.

En Windows Vista y versiones posteriores, el Control de cuentas de usuario (UAC) determina los privilegios de un usuario. Si es miembro del grupo Administradores integrados, se le asignarán dos símbolos (tokens) de acceso en tiempo de ejecución: un símbolo (token) de acceso de usuario estándar y un símbolo (token) de acceso de administrador. De forma predeterminada, se le asignará el rol de usuario estándar. Para ejecutar el código que accede a los contadores de rendimiento, primero debe elevar los privilegios del usuario estándar al administrador. Para ello, inicie una aplicación haciendo clic con el botón derecho en el icono de la aplicación e indique que desea ejecutarla como administrador.

Consulte también

Se aplica a

CounterExists(String, String, String)

Source:
PerformanceCounterCategory.cs
Source:
PerformanceCounterCategory.cs
Source:
PerformanceCounterCategory.cs

Determina si el contador especificado está registrado en la categoría especificada de un equipo remoto.

public:
 static bool CounterExists(System::String ^ counterName, System::String ^ categoryName, System::String ^ machineName);
public static bool CounterExists (string counterName, string categoryName, string machineName);
static member CounterExists : string * string * string -> bool
Public Shared Function CounterExists (counterName As String, categoryName As String, machineName As String) As Boolean

Parámetros

counterName
String

Nombre del contador de rendimiento que se va a buscar.

categoryName
String

Nombre de la categoría de contador de rendimiento u objeto de rendimiento al que está asociado el contador de rendimiento especificado.

machineName
String

Nombre del equipo en el que residen la categoría del contador de rendimiento y los contadores asociados.

Devoluciones

Es true si el contador está registrado en la categoría especificada del equipo especificado; de lo contrario, es false.

Excepciones

El valor de categoryName es null.

o bien

El valor de counterName es null.

categoryName es una cadena vacía ("").

o bien

machineName no es válido.

El nombre de categoría especificado no existe.

Se ha producido un error en la llamada a una API del sistema subyacente.

Código que se ejecuta sin privilegios administrativos para intentar leer un contador de rendimiento.

Ejemplos

En el ejemplo de código siguiente se determina si existe .PerformanceCounter Obtiene un nombre de categoría, un nombre de contador y un nombre de equipo de la línea de comandos, si se proporcionan. Usa las sobrecargas estáticas del CounterExists método para determinar si el nombre especificado PerformanceCounter existe en .PerformanceCounterCategory La sobrecarga se selecciona en función de si se proporciona un nombre de equipo.

public static void Main(string[] args)
{
    string categoryName = "";
    string counterName = "";
    string machineName = "";
    bool objectExists = false;

    // Copy the supplied arguments into the local variables.
    try
    {
        categoryName = args[0];
        counterName = args[1];
        machineName = args[2]=="."? "": args[2];
    }
    catch(Exception ex)
    {
        // Ignore the exception from non-supplied arguments.
    }

    try
    {
        // Check whether the specified counter exists.
        // Use the static forms of the CounterExists method.
        if (machineName.Length==0)
        {
            objectExists = PerformanceCounterCategory.CounterExists(counterName, categoryName);
        }
        else
        {
            objectExists = PerformanceCounterCategory.CounterExists(counterName, categoryName, machineName);
        }
    }
    catch(Exception ex)
    {
        Console.WriteLine("Unable to check for the existence of " +
            "counter \"{0}\" in category \"{1}\" on " +
            (machineName.Length>0? "computer \"{2}\".": "this computer.") + "\n" +
            ex.Message, counterName, categoryName, machineName);
        return;
    }

    // Tell the user whether the counter exists.
    Console.WriteLine("Counter \"{0}\" "+ (objectExists? "exists": "does not exist") +
        " in category \"{1}\" on " + (machineName.Length>0? "computer \"{2}\".": "this computer."),
        counterName, categoryName, machineName);
}
Sub Main(ByVal args() As String)
    Dim categoryName As String = ""
    Dim counterName As String = ""
    Dim machineName As String = ""
    Dim objectExists As Boolean = False

    ' Copy the supplied arguments into the local variables.
    Try
        categoryName = args(0)
        counterName = args(1)
        machineName = IIf(args(2) = ".", "", args(2))
    Catch ex As Exception
        ' Ignore the exception from non-supplied arguments.
    End Try

    Try
        ' Check whether the specified counter exists.
        ' Use the static forms of the CounterExists method.
        If machineName.Length = 0 Then
            objectExists = PerformanceCounterCategory.CounterExists( _
                counterName, categoryName)
        Else
            objectExists = PerformanceCounterCategory.CounterExists( _
                counterName, categoryName, machineName)
        End If

    Catch ex As Exception
        Console.WriteLine("Unable to check for the existence of " & _
            "counter ""{0}"" in category ""{1}"" on " & _
            IIf(machineName.Length > 0, _
            "computer ""{2}"".", "this computer.") & vbCrLf & _
            ex.Message, counterName, categoryName, machineName)
        Return
    End Try

    ' Tell the user whether the counter exists.
    Console.WriteLine("Counter ""{0}"" " & _
        IIf(objectExists, "exists", "does not exist") & _
        " in category ""{1}"" on " & _
        IIf(machineName.Length > 0, _
            "computer ""{2}"".", "this computer."), _
        counterName, categoryName, machineName)
End Sub

Comentarios

Nota

Para leer contadores de rendimiento de una sesión de inicio de sesión no interactiva en Windows Vista y versiones posteriores, Windows XP Professional x64 Edition o Windows Server 2003, debe ser miembro del grupo Usuarios de Monitor de rendimiento o tener privilegios administrativos.

Para evitar tener que elevar los privilegios para acceder a los contadores de rendimiento en Windows Vista y versiones posteriores, agréguese al grupo usuarios de Monitor de rendimiento.

En Windows Vista y versiones posteriores, el Control de cuentas de usuario (UAC) determina los privilegios de un usuario. Si es miembro del grupo Administradores integrados, se le asignarán dos símbolos (tokens) de acceso en tiempo de ejecución: un símbolo (token) de acceso de usuario estándar y un símbolo (token) de acceso de administrador. De forma predeterminada, se le asignará el rol de usuario estándar. Para ejecutar el código que accede a los contadores de rendimiento, primero debe elevar los privilegios del usuario estándar al administrador. Para ello, inicie una aplicación haciendo clic con el botón derecho en el icono de la aplicación e indique que desea ejecutarla como administrador.

Consulte también

Se aplica a