Sunday, September 27, 2009

How to create a virtual drive

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, change caption of Button1 to CreateDrive and the caption of Button2 to RemoveDrive, paste the fallowing 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 fallowing code
  DriveLinkCreate('W', 'D:\Delphi\Components');

replace 'D:\Delphi\Components' with your delphi component folder
press F12 again and double-click the RemoveDrive button and paste this code
  DriveLinkRemove('W');

Don't forget to add ShellApi to uses clause.
That's it, if you have any questions don't hesitate to ask.

2 comments:

  1. Update the code to use widestring: GetSystemDirectoryW() and PWideChar :)

    ReplyDelete
  2. :-) if you're using Delphi 2009+ you don't have to use explicit Wide functions... before Delphi 2009 the ANSI versions of methods was called by Default but from 2009 you call the Wide version of the method UNLESS you call explicitly GetSystemDirectoryA for example or use PAnsiChar

    ReplyDelete

Blogroll(General programming and Delphi feeds)