C# 奇数System.Net.NetworkInformation.NetworkInformation异常

C# 奇数System.Net.NetworkInformation.NetworkInformation异常,c#,linq,exception,networking,C#,Linq,Exception,Networking,以下表达式偶尔引发以下异常: NetworkInterface[] interfacesToUse = (from outer in NetworkInterface.GetAllNetworkInterfaces() select outer).ToArray(); IPv4InterfaceStatistics[] stats = (from current in interfacesToU

以下表达式偶尔引发以下异常:

NetworkInterface[] interfacesToUse = (from outer in NetworkInterface.GetAllNetworkInterfaces()
                                                  select outer).ToArray();

IPv4InterfaceStatistics[] stats = (from current in interfacesToUse select current.GetIPv4Statistics()).ToArray();
基本异常类型: System.Net.NetworkInformation.NetworkInformation异常 (0x80004005):系统找不到在处指定的文件 System.Net.NetworkInformation.SystemIPv4InterfaceStatistics.GetIfEntry(Int64 索引)在 System.Net.NetworkInformation.SystemNetworkInterface.GetIPv4Statistics() 在System.Linq.Enumerable.WhereSelectArrayIterator
2.MoveNext()中
System.Linq.Buffer
1..ctor(IEnumerable
1源代码)位于
System.Linq.Enumerable.ToArray[TSource](IEnumerable
1源)

堆栈跟踪:在 System.Net.NetworkInformation.SystemIPv4InterfaceStatistics.GetIfEntry(Int64 索引)在 System.Net.NetworkInformation.SystemNetworkInterface.GetIPv4Statistics() 在System.Linq.Enumerable.WhereSelectArrayIterator
2.MoveNext()中
System.Linq.Buffer
1..ctor(IEnumerable
1源代码)位于
System.Linq.Enumerable.ToArray[TSource](IEnumerable
1源)

我一直找不到任何可以提供此错误一些见解的文档

偶尔

我想知道为什么它偶尔发生。您是否使用如图所示的代码?来自.NET 3.5的方法
SystemIPv4InterfaceStatistics.GetIfEntry(Int64索引)
,调用
iphlapi.dll
中的函数。从.NET4开始,调用该函数。根据堆栈跟踪,我假设您使用的是.NET3.5

将未知索引传递到
GetIfEntry()
时,返回错误2,该错误被转换为“系统找不到指定的文件”(但实际上只是
Error\u NOT\u FOUND

这不应该发生在.NET中,因为
NetworkInterface.GetAllNetworkInterfaces()
应该只返回系统已知的网络接口,因此它们的所有(私有)
index
属性都应该设置为系统已知的索引


编辑:使用以下代码再现错误:

var interfaces = NetworkInterface.GetAllNetworkInterfaces();

while (true)
{

    foreach (var i in interfaces)
    {
        var s = i.GetIPv4Statistics();

        Console.WriteLine("Received: {0}, Sent: {1}", s.BytesReceived, s.BytesSent);
    }                
}
当我启动VPN连接时,我有一个额外的接口,它将被打印出来。第二次禁用此连接时,该接口上的
GetIPv4Statistics()
将抛出您提到的异常


我想这取决于你在运行代码的机器上做了什么。我想每次您想要获取接口数据时都必须调用
NetworkInterface.GetAllNetworkInterfaces()

我在while循环外设置interfacesToUse,然后每隔几秒钟迭代一次以获取统计数据。我正在使用的项目是根据.NET4.0构建的。