Querying win32_NetworkConnection is slow on Windows 7

1k Views Asked by At

Folks,

For years, I've been happily using the below C# IsNetworkDrive method to determine "Is this a network drive?" under Windows XP. It still produces the expected result under Windows 7, but it takes something in the order of 10 seconds for each call... ergo about a million times too long!

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. I hate Windows!

Please does anybody have any ideas how to [performantly] determine if a given drive letter represents a local drive or a network drive, on both Windows 7 and Windows XP (corporate SOE's)????

[Preferably in .NET <= 3.5, though I COULD upgrade the project to 4.0, it'd just require a green-fields test, which we don't have the money for right now. Sigh.]

Cheers all. Keith.

1

There are 1 best solutions below

0
On

I'm answering my own question.

A bit more googling lead me to this post: How to programmatically discover mapped network drives on system and their server names?

And the code in that question leads me to: DriveInfo.GetDrives() which I work into my main method:

    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();
    }

to produce:

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 ...

... and then it's not far from there to:

    // 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;
    }

which produces the expected results in the expected [sub-second] timeframe under Windows 7, running as a non-administrator.

Hope this helps someone else out.

Cheers all. Keith.