Skip to content

Instantly share code, notes, and snippets.

@wojciech-kulik
Last active December 16, 2015 18:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wojciech-kulik/27794df74792a5f976a4 to your computer and use it in GitHub Desktop.
Save wojciech-kulik/27794df74792a5f976a4 to your computer and use it in GitHub Desktop.
GetSingleInstanceCounter
[DllImport("pdh.dll", SetLastError = true, CharSet = CharSet.Unicode)]
static extern UInt32 PdhLookupPerfNameByIndex(string szMachineName, uint dwNameIndex, StringBuilder szNameBuffer, ref uint pcchNameBufferSize);
PerformanceCounter GetSingleInstanceCounter(string englishCategoryName, string englishCounterName)
{
// Try first with english names
try
{
return new PerformanceCounter(englishCategoryName, englishCounterName);
}
catch { }
// Get list of counters
const string perfCountersKey = @"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Perflib\009";
var englishNames = Registry.GetValue(perfCountersKey, "Counter", null) as string[];
// Get localized category name
var localizedCategoryId = FindNameId(englishNames, englishCategoryName);
var localizedCategoryName = GetNameByIndex(localizedCategoryId);
// Get localized counter name
var localizedCounterId = FindNameId(englishNames, englishCounterName);
var localizedCounterName = GetNameByIndex(localizedCounterId);
return GetCounterIfExists(localizedCategoryName, localizedCounterName) ??
GetCounterIfExists(localizedCategoryName, englishCounterName) ??
GetCounterIfExists(englishCategoryName, localizedCounterName);
}
PerformanceCounter GetCounterIfExists(string categoryName, string counterName)
{
try
{
return new PerformanceCounter(categoryName, counterName);
}
catch
{
return null;
}
}
int FindNameId(string[] englishNames, string name)
{
// englishNames contains alternately id and name, that's why I check only odd lines
for (int i = 1; i < englishNames.Length; i += 2)
{
if (englishNames[i] == name)
{
return Int32.Parse(englishNames[i - 1]);
}
}
return -1;
}
string GetNameByIndex(int id)
{
if (id < 0)
{
return null;
}
var buffer = new StringBuilder(1024);
var bufSize = (uint)buffer.Capacity;
var ret = PdhLookupPerfNameByIndex(null, (uint)id, buffer, ref bufSize);
return ret == 0 && buffer.Length != 0 ? buffer.ToString() : null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment