Author: William Gerbert
Enumerate all network resources
Answer:
The following routine DoEnumeration enumerates all network resources and puts the
server names in a listbox ListBox1. In the given application this was used to
select an application server.
1
2 function Fix(Server: string): string;
3 var
4 p: integer;
5 begin { Fix }
6 // dirty & slow, but it works :-)
7 while copy(Server, 1, 1) = '\' do
8 delete(Server, 1, 1);
9 p := pos('\', Server);
10 if p > 0 then
11 delete(Server, p, 999);
12
13 Result := Server
14 end; { Fix }
15
16 procedure TFSelServer.DoEnumeration;
17 type
18 PNetResourceArray = ^TNetResourceArray;
19 TNetResourceArray = array[0..MaxInt div SizeOf(TNetResource) - 1] of TNetResource;
20 var
21 I, Count, BufSize, Size, NetResult: Integer;
22 NetHandle: THandle;
23 NetResources: PNetResourceArray;
24 Server: string;
25 begin { DoEnumeration }
26 if WNetOpenEnum(RESOURCE_CONNECTED, RESOURCETYPE_ANY, 0, nil, NetHandle) <>
27 NO_ERROR
28 then
29 Exit;
30
31 try
32 BufSize := 50 * SizeOf(TNetResource);
33 GetMem(NetResources, BufSize);
34 try
35 while True do
36 begin { while Tr.. }
37 Count := -1;
38 Size := BufSize;
39 NetResult := WNetEnumResource(NetHandle, Count, NetResources, Size);
40 if NetResult = ERROR_MORE_DATA then
41 begin
42 BufSize := Size;
43 ReallocMem(NetResources, BufSize);
44 Continue;
45 end;
46 if NetResult <> NO_ERROR then
47 Exit;
48 for I := 0 to Count - 1 do
49 with NetResources^[I] do
50 begin { with Net.. }
51 Server := Fix(lpRemoteName);
52 if ListBox1.Items.IndexOf(Server) < 0 then
53 ListBox1.Items.Add(Server)
54 end; { with Net.. }
55 end; { while Tr.. }
56 finally
57 FreeMem(NetResources, BufSize);
58 end; { try }
59 finally
60 WNetCloseEnum(NetHandle);
61 end; { try }
62 end; { DoEnumeration }
|