반응형
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] 
public class NETRESOURCE 
{ 
public uint dwScope; 
public uint dwType; 
public uint dwDisplayType; 
public uint dwUsage; 
public string lpLocalName; 
public string lpRemoteName; 
public string lpComment; 
public string lpProvider; 
} 
public const uint  RESOURCE_CONNECTED     = 0x00000001;
public const uint  RESOURCE_GLOBALNET     = 0x00000002;
public const uint  RESOURCE_REMEMBERED    = 0x00000003;
public const uint  RESOURCE_RECENT        = 0x00000004;
public const uint  RESOURCE_CONTEXT       = 0x00000005;

public const uint  RESOURCETYPE_ANY       = 0x00000000;
public const uint  RESOURCETYPE_DISK      = 0x00000001;
public const uint  RESOURCETYPE_PRINT     = 0x00000002;

public const uint  RESOURCEUSAGE_CONNECTABLE  = 0x00000001;
public const uint  RESOURCEUSAGE_CONTAINER    = 0x00000002;
public const uint  RESOURCEUSAGE_ATTACHED     = 0x00000010;
public const uint  RESOURCEUSAGE_ALL          = (RESOURCEUSAGE_CONNECTABLE | 
                                                 RESOURCEUSAGE_CONTAINER | 
                                                 RESOURCEUSAGE_ATTACHED);
[DllImport("mpr.dll", CharSet=CharSet.Auto)]
public static extern int WNetOpenEnum(uint dwScope, uint dwType, uint dwUsage,
    [MarshalAs(UnmanagedType.LPStruct)] NETRESOURCE lpNetResource,
    out IntPtr lphEnum);
[DllImport("mpr.dll", CharSet=CharSet.Auto)]
public static extern int WNetEnumResource(IntPtr hEnum, ref int lpcCount, 
    IntPtr lpBuffer, ref int lpBufferSize);
[DllImport("mpr.dll", CharSet=CharSet.Auto)]
public static extern int WNetCloseEnum(IntPtr hEnum);
public static NETRESOURCE[] GetNetworkDriveList()
{
    int result;
    int nrCount = -1;
    int bufferSize = 4*1024;
    NETRESOURCE nr = null;
    int itemSize = Marshal.SizeOf(typeof(NETRESOURCE));
    ArrayList items = new ArrayList();
    int count, size;
    IntPtr buffer;
    IntPtr hEnum;

    result = WNetOpenEnum(RESOURCE_CONNECTED, RESOURCETYPE_DISK, 0, null, out hEnum);

    buffer = Marshal.AllocHGlobal(bufferSize);
    try {
        while(true) {
            count = nrCount;
            size = bufferSize;
            result = WNetEnumResource(hEnum, ref count, buffer, ref size);
            if (result == 259)        // ERROR_NO_MORE_ITEMS
                break;
            IntPtr curPos = buffer;
            for(int i=0; i < count; i++) {
                nr = (NETRESOURCE)Marshal.PtrToStructure(curPos, typeof(NETRESOURCE));
                items.Add(nr);
                curPos = new IntPtr(curPos.ToInt32() + itemSize);
            }
        }
    }
    finally {
        Marshal.FreeHGlobal(buffer);
        WNetCloseEnum(hEnum);
    }
    return (NETRESOURCE[])items.ToArray(typeof(NETRESOURCE));
}

+ Recent posts