You can use the Exists method on the PerformanceCounter 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 CategoryExists method on the PerformanceCounter class. You might do this if you are creating a custom counter and want to determine if the category for it already exists. The CreateCategory method will raise an error if the category you specify has already been created.
Note You can also use the Exists method on the PerformanceCounterCategory class to determine whether a category exists. Both methods function identically, so use whichever object is most convenient for you.
Both the Exists and the CategoryExists methods return true if the item is found, and false if it is not.
To determine if a counter exists
Parameter | Value |
---|---|
CategoryName | Any category of performance objects on the server. |
CounterName | The name of the counter you want to query. |
MachineName | (Optional) The server on which to locate the category and counter. If blank, the local machine is assumed. |
To determine if a category exists
Parameter | Value |
---|---|
CategoryName | Any category you want to query. |
MachineName | (Optional) The server on which to locate the category. If blank, the local machine is assumed. |
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 (PerformanceCounter1.CategoryExists("MyCat")) Then PerformanceCounter1.CreateCategory "MyCat","Desc","MyCtr","Desc" End If [C#] [C#] if (!PerformanceCounter1.CategoryExists("MyCat")){ PerformanceCounter1.CreateCategory ("MyCat","Desc","MyCtr","Desc"); }