以下表达式偶尔会引发以下异常:
NetworkInterface[] interfacesToUse = (from outer in NetworkInterface.GetAllNetworkInterfaces()
select outer).ToArray();
IPv4InterfaceStatistics[] stats = (from current in interfacesToUse select current.GetIPv4Statistics()).ToArray();
Base Exception Type: System.Net.NetworkInformation.NetworkInformationException (0x80004005): The system cannot find the file specified at System.Net.NetworkInformation.SystemIPv4InterfaceStatistics.GetIfEntry(Int64 index) at System.Net.NetworkInformation.SystemNetworkInterface.GetIPv4Statistics() at System.Linq.Enumerable.WhereSelectArrayIterator
2.MoveNext() at System.Linq.Buffer
1..ctor(IEnumerable1 source) at System.Linq.Enumerable.ToArray[TSource](IEnumerable
1 source)Stack Trace: at System.Net.NetworkInformation.SystemIPv4InterfaceStatistics.GetIfEntry(Int64 index) at System.Net.NetworkInformation.SystemNetworkInterface.GetIPv4Statistics() at System.Linq.Enumerable.WhereSelectArrayIterator
2.MoveNext() at System.Linq.Buffer
1..ctor(IEnumerable1 source) at System.Linq.Enumerable.ToArray[TSource](IEnumerable
1 source)
我无法找到任何可以提供有关此错误的见解的文档。
最佳答案
occasionally
我想知道为什么有时会发生这种情况。您使用如图所示的代码吗?来自 .NET 3.5 的方法 SystemIPv4InterfaceStatistics.GetIfEntry(Int64 index)
调用 GetIfEntry
Iphlpapi.dll 中的函数。从 .NET 4 开始,函数 GetIfEntry2
叫做。根据您的堆栈跟踪,我假设您正在使用 .NET 3.5。
当未知索引传递到 GetIfEntry()< 时,会返回错误 2,它被翻译为“系统找不到指定的文件”(但实际上只是
.ERROR_NOT_FOUND
)/
这在 .NET 中不应该发生,因为 NetworkInterface.GetAllNetworkInterfaces()
应该只返回系统已知的网络接口(interface),因此它们的所有(私有(private))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 连接时,我会打印一个额外的界面。当我禁用此连接时,该接口(interface)上的 GetIPv4Statistics()
将抛出您提到的异常。
我想这取决于您在运行此代码的机器上所做的事情。我认为每次想要获取接口(interface)数据时都必须调用 NetworkInterface.GetAllNetworkInterfaces() 。
关于c# - 奇怪的 System.Net.NetworkInformation.NetworkInformationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12987589/