日期:2011-07-10  浏览次数:20413 次

最近一项目中要求显示网络流量,而且必须使用C#。

事实上,调用 IpHlpApi.dll 的 GetIfTable API 可以轻易获得网络信息和网络流量。只是要在C#中实现还是比较复杂。

先看看怎么定义该 API
[DllImport("IpHlpApi.dll")]
        extern static public uint GetIfTable(byte[] pIfTable, ref uint pdwSize, bool bOrder);
本来想把 pIfTable 定义为 IntPtr,但是这样的结果是,获取的信息是错误的(直到现在都不知是什么原因)。

但显然定义为 byte[] 是不能直接使用的。幸好在 Google Code Search 找到了三个类:

CustomtMarshaler.cs
using System;
using System.IO;
using System.Collections;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;

namespace Lemony.SystemInfo
{
   
    /**//// <summary>
    /// CustomMarshaler class implementation.
    /// </summary>
    public abstract class CustomMarshaler
    {
        Fields#region Fields
        // The internal buffer
        internal byte[] data;
        private MemoryStream stream;
        private BinaryReader binReader;
        private BinaryWriter binWriter;
       
        #endregion
   
        constructors#region constructors

        public CustomMarshaler()
        {

        }
       
        #endregion

        public methods#region public methods

        public void Deserialize()
        {
            if (data != null)
            {
                if (binReader != null)
                {
                    binReader.Close();
                    stream.Close();
                }
                // Create a steam from byte array
                stream = new MemoryStream(data);
                binReader = new BinaryReader(stream, System.Text.Encoding.Unicode);
                ReadFromStream(binReader);
                binReader.Close();
            }

        }

        public void Serialize()
   &nbs