在Windows 7上查询win32_NetworkConnection很慢

时间:2012-05-14 00:32:27

标签: c# windows-7 windows-xp-sp2

民间,

多年来,我一直很高兴使用下面的C# IsNetworkDrive 方法来确定“这是一个网络驱动器吗?”在Windows XP下。它仍然在Windows 7下产生预期的结果,但每次通话需要大约10秒的时间......大约一百万次太长了!

using System;
using System.Collections.Generic;
using System.Management;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            foreach (var driveName in Environment.GetLogicalDrives())
                Console.WriteLine(driveName + " " + IsNetworkDrive(driveName.Substring(0,2)));
            Console.Write("Press any key to continue ...");
            Console.ReadKey();
        }

        private static bool IsNetworkDrive(string drive)
        {
            var query = @"SELECT Name FROM win32_NetworkConnection WHERE LocalName='" + drive + "'";
            var seacher = new ManagementObjectSearcher(query);
            var resultset = seacher.Get();
            var count = resultset.Count;
            return count == 1;
        }

    }
}

Arrrgggghhhh。我讨厌Windows!

请不要有任何想法如何[在Windows 7和Windows XP(公司SOE)上[确定]确定给定的驱动器号是代表本地驱动器还是网络驱动器?

[最好在.NET< = 3.5,虽然我可以将项目升级到4.0,但它只需要一个绿色字段测试,我们现在没有钱。叹息。]

干杯。基思。

1 个答案:

答案 0 :(得分:1)

我正在回答我自己的问题。

更多谷歌搜索引导我阅读这篇文章:How to programmatically discover mapped network drives on system and their server names?

该问题中的代码引导我: DriveInfo.GetDrives(),我将其用于我的主要方法:

    static void Main(string[] args) {
        foreach (var driveInfo in DriveInfo.GetDrives())
            Console.WriteLine(driveInfo + " " + driveInfo.DriveType);
        Console.Write("Press any key to continue ...");
        Console.ReadKey();
    }

生产:

C:\ Fixed
D:\ CDRom
E:\ Removable
G:\ Network
H:\ Network
I:\ Network
K:\ Network
L:\ Network
M:\ Network
Q:\ Network
Press any key to continue ...

......然后离那里不远:

    // Example drives: "C:" or "L:" ... just the drive-letter and a colon. No backslash. 
    private static bool IsNetworkDrive(string drive) {
        return new DriveInfo(drive).DriveType == DriveType.Network;
    }

在Windows 7下的预期[sub-second]时间范围内产生预期结果,以非管理员身份运行。

希望这可以帮助其他人。

干杯。基思。