Calculating Bandwidth

前端 未结 5 1034
无人共我
无人共我 2020-11-27 14:54

Is there any way i can calculate bandwidth (packets sent and received) by an exe/application via net? have looked into IPGlobalProperties, and other classes.

I want

5条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-27 15:28

    One way is to retrieve the value of the performance counters ".NET CLR Networking/Bytes Received" and ".NET CLR Networking/Bytes Sent" for your application:

    PerformanceCounter bytesSentPerformanceCounter= new PerformanceCounter();
    bytesSentPerformanceCounter.CategoryName = ".NET CLR Networking";
    bytesSentPerformanceCounter.CounterName = "Bytes Sent";
    bytesSentPerformanceCounter.InstanceName = GetInstanceName();
    bytesSentPerformanceCounter.ReadOnly = true;
    
    float bytesSent = bytesSentPerformanceCounter.NextValue();
    
    //....
    
    private 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);
    }
    
    private 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;
    }
    

    Note that the performance-counters aren't created until the first time you use the relevant network libraries (you will get InvalidOperation : Instance 'XXX' does not exist in the specified Category) and that you need to insert

    
      
        
          
        
      
    
    

    in your app.config.

    For a full sample download NetworkTraffic.cs and NetworkTraffic.exe.config.

提交回复
热议问题