How to create a virtual drive #229

This is a very simple method to create a new drive which links to a folder. For example: let's say we want a new drive letter (W) which points to our Delphi components folder (D:\Delphi\Components\).

Create a new VCL application. Drop 2 buttons on the form and change the caption of Button1 to CreateDrive and the caption of Button2 to RemoveDrive. Paste the following 3 methods after the implementation keyword.

function SystemDir: string;
begin
  (* get system32 folder *)
  SetLength(Result, MAX_PATH);
  GetSystemDirectory(@Result[1], MAX_PATH);
end;
 
procedure DriveLinkCreate(const Drive: Char; const Path: String);
var
  Param: String;
begin
  (* format the call parameter *)
  Param := Format('%s: "%s"', [Drive, Path]);
  (* and bang! we get a new drive *)
  ShellExecute(1, 'open', 'subst', PChar(Param),
    PChar(SystemDir), 0);
end;
 
procedure DriveLinkRemove(const Drive: Char);
var
  Param: String;
begin
  (* format the call parameter with the /d option
     which stands for delete *)
  Param := Format('%s: /d', [Drive]);
  (* now we remove the virtual drive *)
  ShellExecute(1, 'open', 'subst', PChar(Param),
    PChar(SystemDir), 0);
end;

Now press F12 to see the form, double-click the CreateDrive button and paste the following code into the event handler that is created:

  DriveLinkCreate('W', 'D:\Delphi\Components');

Replace D:\Delphi\Components with your own Delphi component folder. Press F12 again, double-click the RemoveDrive button and paste the following code into its event handler:

  DriveLinkRemove('W');

Finally, add the ShellApi unit to the uses clause.

Original resource:
Author: Dorin Duminica
Contributor: topellina
Added: 2013/09/06
Last updated: 2013/09/06