Archive

Archive for April 26, 2014

Getting a list of mapped network drives

April 26, 2014 Leave a comment

Continuing the theme of mapped network drives (see earlier post about how to connect a network drive by code), here is another class that is quite helpful. In short, it simply queries the operative system for mapped network paths and their drive letter.

Very simply to use: just create an instance, call the refresh method (this is called automatically by the constructor) and use the properties to traverse the list.

 


  TQTXNetworkDriveList = Class(TObject)
  Private
    FObjects:   TStringList;
    Function    GetCount:Integer;
    Function    GetItem(index:Integer):String;
    Function    GetDriveLetter(index:Integer):String;
    Function    GetMapPath(index:Integer):String;
  Public
    Property    Count:Integer read GetCount;
    Property    DriveLetter[index:Integer]:String read GetDriveLetter;
    Property    MapPath[index:Integer]:String read GetMapPath;
    Property    Items[index:Integer]:String read GetItem;default;
  Public
    Procedure   Refresh;
    function    toString:String;override;
    Procedure   AfterConstruction;override;
    Constructor Create;
    Destructor  Destroy;Override;
  End;

//##########################################################################
// TQTXNetworkDriveList
//##########################################################################

Constructor TQTXNetworkDriveList.Create;
Begin
  inherited;
  FObjects:=TStringList.Create;
end;

Destructor TQTXNetworkDriveList.Destroy;
Begin
  FObjects.free;
  inherited;
end;

Procedure TQTXNetworkDriveList.AfterConstruction;
Begin
  inherited;
  Refresh;
end;

function TQTXNetworkDriveList.toString:String;
begin
  result:=FObjects.Text;
end;

Function TQTXNetworkDriveList.GetDriveLetter(index:Integer):String;
Begin
  result:=FObjects.Names[index] + ':';
end;

Function TQTXNetworkDriveList.GetMapPath(index:Integer):String;
Begin
  result:=FObjects.Values[FObjects.Names[index]];
end;

Function TQTXNetworkDriveList.GetCount:Integer;
Begin
  result:=FObjects.Count;
end;

Function TQTXNetworkDriveList.GetItem(index:Integer):String;
Begin
  result:=GetDriveLetter(index) + getMapPath(index);
end;

Procedure TQTXNetworkDriveList.Refresh;
const
  CNT_DRIVEMASK = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var
  i:      integer;
  mPath:  string;
  mLen:   DWord;
  mDrive: String;
Begin
  FObjects.Clear;
  for i:=1 to length(CNT_DRIVEMASK) do
  Begin
    mDrive:=CNT_DRIVEMASK[i] + ':';
    mLen := MAX_PATH;
    SetLength(mPath,MAX_PATH);
    If NO_ERROR=WNetGetConnection(PChar(mDrive),PChar(mPath),mLen) then
    FObjects.Values[CNT_DRIVEMASK[i]]:=copy(mPath,1,mLen);
  end;
end;