c# - 奇怪的 System.Net.NetworkInformation.NetworkInformationException

标签 c# linq exception networking

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

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.WhereSelectArrayIterator2.MoveNext() at System.Linq.Buffer1..ctor(IEnumerable1 source) at System.Linq.Enumerable.ToArray[TSource](IEnumerable1 source)

Stack Trace: at System.Net.NetworkInformation.SystemIPv4InterfaceStatistics.GetIfEntry(Int64 index) at System.Net.NetworkInformation.SystemNetworkInterface.GetIPv4Statistics() at System.Linq.Enumerable.WhereSelectArrayIterator2.MoveNext() at System.Linq.Buffer1..ctor(IEnumerable1 source) at System.Linq.Enumerable.ToArray[TSource](IEnumerable1 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/

相关文章:

c# - 使用 Json.NET 将嵌套的 JSON 反序列化为平面类

c# - Resharper (2016.1 C#) 可以建议用 try catch block 捕获异常吗?

c# - MVC .Net View 嵌套模型列表

c# - 寻找 mainviewmodel 上 MVVM 文本 block 绑定(bind)的指导

c# - FluentMongo LINQ : How to query a sublist of a class

c# - 引用非标量闭包 c#

c# - (obj != null) 不起作用

c# - 引发异常或返回错误 - 更好的方法是什么?

c# - 处理任务并行库中的异常

c# - Button.OnCommand += new CommandEventHandler 结果保护级别错误