Export (0) Print
Expand All

Determining If Counters and Categories Exist

You can use the CounterExists method on the PerformanceCounterCategory class to determine if a given performance counter exists within a particular category on either the local or a remote computer. You might do this before creating a new counter to prevent an error from occurring if another counter with that name exists.

In addition to determining whether counters exist, you can determine whether a given category exists by using the Exists method on the PerformanceCounterCategory class. You might do this if you are creating a custom counter and want to determine if the category for it already exists. The Create method will raise an error if the category you specify has already been created.

Both the Exists and the CounterExists methods return true if the item is found and false if it is not.

To determine if a counter exists

  • Call the CounterExists method on the PerformanceCounterCategory class, specifying the following parameters.
    ParameterValue
    CounterNameThe name of the counter you want to query.
    CategoryNameAny category of performance objects on the server.
    MachineNameThe server on which to locate the category and counter.
Note   In Visual Basic, the MachineName parameter is optional; if left blank it defaults to the local machine. In C#, you can use an overload of the CounterExists method if you do not want to specify the machine name.

To determine if a category exists

  • Call the Exists method on the PerformanceCounterCategory class, specifying the following parameters.
    ParameterValue
    CategoryNameAny category you want to query.
    MachineNameThe server on which to locate the category.

    The following example shows how to use an If statement to determine whether a category exists before creating a category and counter:

    ' Visual Basic
    If Not (PerformanceCounterCategory.Exists("MyCat")) Then
       PerformanceCounterCategory.Create( _
          "MyCat", "Description", "MyCounter", "Description")
    End If
    
    // C#
    if (!System.Diagnostics.PerformanceCounterCategory.Exists("MyCat"))
    {
       System.Diagnostics.PerformanceCounterCategory.Create(
          "MyCat", "Description", "MyCounter", "Description");
    }
    

See Also

Category and Counter Management | Writing Values to Performance Counters | Performance Counter Value Retrieval

Show:
© 2015 Microsoft