How to: Determine If Counters and Categories Exist

[This documentation is for preview only, and is subject to change in later releases. Blank topics are included as placeholders.]

You can use the CounterExists method on the PerformanceCounterCategory class to determine whether a given performance counter exists in 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 whether 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 whether 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.

    Note

    In Visual Basic, the MachineName parameter is optional; if left blank, by default it uses 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 whether 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");
            }
    

See Also

Tasks

How to: Write Values to Performance Counters

Concepts

Category and Counter Management

Performance Counter Value Retrieval