I am following the answer here:
Calculating Bandwidth
And implemented everything like he said. My monitor is initialized like so:
netSentCounter.CategoryName = ".NET CLR Networking";
netSentCounter.CounterName = "Bytes Sent";
netSentCounter.InstanceName = Misc.GetInstanceName();
netSentCounter.ReadOnly = true;
I can corrently see that Misc.GetInstanceName()
returns "MyProcessName[id]". However I keep getting the exception that the instance doesn't exist in the specified category.
My understanding is that the category for net sent/received isn't created until you actually send or receive.
I have added the app.config as described in the answer like so:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.net>
<settings>
<performanceCounters enabled="true" />
</settings>
</system.net>
</configuration>
Why do I still get an error?
Here is my monitoring code:
public static class Monitoring
{
private static PerformanceCounter netSentCounter = new PerformanceCounter();
//Static constructor
static Monitoring()
{
netSentCounter.CategoryName = ".NET CLR Networking";
netSentCounter.CounterName = "Bytes Sent";
netSentCounter.InstanceName = Misc.GetInstanceName();
netSentCounter.ReadOnly = true;
}
/// <summary>
/// Returns the amount of data sent from the current application in MB
/// </summary>
/// <returns></returns>
public static float getNetSent()
{
return (float)netSentCounter.NextValue() / 1048576; //Convert to from Bytes to MB
}
}
And my Misc class:
public static class Misc
{
//Returns an instance name
internal static string GetInstanceName()
{
// Used Reflector to find the correct formatting:
string assemblyName = GetAssemblyName();
if ((assemblyName == null) || (assemblyName.Length == 0))
{
assemblyName = AppDomain.CurrentDomain.FriendlyName;
}
StringBuilder builder = new StringBuilder(assemblyName);
for (int i = 0; i < builder.Length; i++)
{
switch (builder[i])
{
case '/':
case '\\':
case '#':
builder[i] = '_';
break;
case '(':
builder[i] = '[';
break;
case ')':
builder[i] = ']';
break;
}
}
return string.Format(CultureInfo.CurrentCulture,
"{0}[{1}]",
builder.ToString(),
Process.GetCurrentProcess().Id);
}
/// <summary>
/// Returns an assembly name
/// </summary>
/// <returns></returns>
internal static string GetAssemblyName()
{
string str = null;
Assembly entryAssembly = Assembly.GetEntryAssembly();
if (entryAssembly != null)
{
AssemblyName name = entryAssembly.GetName();
if (name != null)
{
str = name.Name;
}
}
return str;
}
}
Edit: I have opened the resource monitor from windows to see what the problem is. The counter isn't being started albeit having the app.config set to do so.
Here is what i see (this before and after my application sending network activity)
And the name isn't what my method is returning. My method returns "SuperScraper[appId]" while in the resource it is called "Superscraper.vshost.exe".
So I have two problems now:
-My counter isn't starting on app startup -The name is differnet