Question

I came across this excellent article that solves the problem of enumerating disconnected drives in C#: Mapped network drives cannot be listed in C#

The problem is that it seems like this code will NOT include NTFS-formatted drives (only FAT)

As I'm not a C++/WinAPI techie, I find it hard to fix the code (if possible at all). Any chance anyone already look into it and solved it, or at least give me a hint?

Thanks! Busi

Was it helpful?

Solution

OK, I have an answer. It has nothing to do with NTFS and FAT.

This is the code I used to enumerate the drives:

WNetOpenEnum( RESOURCE_SCOPE.RESOURCE_REMEMBERED, RESOURCE_TYPE.RESOURCETYPE_DISK, 0, resource, out ptrHandle);

Please note the first parameter, RESOURCE_SCOPE.RESOURCE_REMEMBERED. This mean that the method will only enumerate those mapped drives that were set as PERSISTED (which means, re-connect at logon).

If I change for example the parameter to RESOURCE_SCOPE.RESOURCE_CONNECTED, it will enumerate the non-persisted drives, if they are connected.

If you want all the combinations, you can do: WNetOpenEnum(RESOURCE_SCOPE.RESOURCE_REMEMBERED | RESOURCE_SCOPE.RESOURCE_RECENT | RESOURCE_SCOPE.RESOURCE_CONNECTED, RESOURCE_TYPE.RESOURCETYPE_DISK, 0, resource, out ptrHandle);

Thank you!

OTHER TIPS

If you want to list your local NTFS drives, the article you mentionned won't cut it : the Win32 functions it uses are meant to enumerate network ressources.

So if you want to list all local drives and network drives, you have to use both the code from your link, and also call DriveInfo.GetDrives() (or Environment.GetDrives()) from the System.IO namespace.

However, since GetDrives() will also return connected network drives, you need to merge the results of both lists to avoid duplicates :

    static void Main(string[] args)
    {
        List<string> drives = new List<string>();
        // Assuming you put the API calls in Class1
        foreach (var item in Class1.WNetResource())
        {
            // WNetResource returns the drive letters without a trailing slash
            drives.Add(String.Concat(item.Key, @"\"));
        }

        foreach (var item in Environment.GetLogicalDrives())
        {
            if (!drives.Contains(item))
                drives.Add(item);
        }

        drives.Sort();

        foreach (var drive in drives)
        {
            Console.WriteLine(drive);
        }
    }

Hope that helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top