Compartilhar via


How to: Determine 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 Exists method on the PerformanceCounterCategory class, specifying the following parameters.

    Parameter Value

    CounterName

    The name of the counter you want to query.

    CategoryName

    Any category of performance objects on the server.

    MachineName

    The server on which to locate the category and counter.

    NoteNote

    In Visual Basic, the MachineName parameter is optional; if left blank it defaults to the local computer. In C#, you can use an overload of the Exists method if you do not want to specify the computer name.

To determine if a category exists

  • Call the Exists method on the PerformanceCounterCategory class, specifying the following parameters.

    Parameter Value

    CategoryName

    Any category you want to query.

    MachineName

    The 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:

    If Not (PerformanceCounterCategory.Exists("MyCat")) Then
        PerformanceCounterCategory.Create( _
           "MyCat", "Description", _
           PerformanceCounterCategoryType.SingleInstance, _
           "MyCounter", "Description")
    End If
    
    if (!System.Diagnostics.PerformanceCounterCategory.Exists("MyCat"))
    {
        System.Diagnostics.PerformanceCounterCategory.Create(
           "MyCat", "Description", PerformanceCounterCategoryType.SingleInstance,
           "MyCounter", "Description");
    }
    
    if (!System.Diagnostics.PerformanceCounterCategory.Exists("MyCat"))
    {
       System.Diagnostics.PerformanceCounterCategory.Create(
          "MyCat", "Description", "MyCounter", "Description");
    }
    

See Also

Tasks

How to: Write Values to Performance Counters

Concepts

Category and Counter Management
Performance Counter Value Retrieval