Bjarke Moholt
Bjarke Moholt

Reputation: 323

Get local name of network share in Delphi

How do I get the local name of a network share in Delphi?

I have a Filepath to the local alias of the network share Z:\someFolder\someFile and am able to expand the UNC path \\server\sharename\someFolder\someFile. However, I need the local path on the remote location F:\sharedFolder\someFolder\someFile

Thank you in advance

Upvotes: 2

Views: 2792

Answers (2)

Ondrej Kelle
Ondrej Kelle

Reputation: 37221

Here's a small example:

program test;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  Windows,
  SysUtils;

const
  netapi = 'netapi32.dll';
  NERR_Success = 0;
  STYPE_DISKTREE  = 0;
  STYPE_PRINTQ    = 1;
  STYPE_DEVICE    = 2;
  STYPE_IPC       = 3;
  STYPE_TEMPORARY = $40000000;
  STYPE_SPECIAL   = $80000000;

function NetApiBufferFree(Buffer: Pointer): DWORD; stdcall; external netapi;
function NetShareGetInfo(servername, netname: PWideChar; level: DWORD; out bufptr: Pointer): DWORD; stdcall;
  external netapi;

type
  PShareInfo2 = ^TShareInfo2;
  TShareInfo2 = record
    shi2_netname: PWideChar;
    shi2_type: DWORD;
    shi2_remark: PWideChar;
    shi2_permissions: DWORD;
    shi2_max_uses: DWORD;
    shi2_current_uses: DWORD;
    shi2_path: PWideChar;
    shi2_passwd: PWideChar;
  end;

function ShareNameToServerLocalPath(const ServerName, ShareName: string): string;
var
  ErrorCode: DWORD;
  Buffer: Pointer;
begin
  Result := '';

  ErrorCode := NetShareGetInfo(PWideChar(ServerName), PWideChar(ShareName), 2, Buffer);
  try
    if ErrorCode = NERR_Success then
      Result := PShareInfo2(Buffer)^.shi2_path;
  finally
    NetApiBufferFree(Buffer);
  end;
end;

procedure Main;
begin
  Writeln(ShareNameToServerLocalPath('\\MyServer', 'MyShare'));
end;

begin
  try
    Main;
  except
    on E: Exception do
    begin
      ExitCode := 1;
      Writeln(Format('[%s] %s', [E.ClassName, E.Message]));
    end;
  end;
end.

Upvotes: 4

SilverWarior
SilverWarior

Reputation: 8396

That is not possible I'm afraid.

Whenever you share some folder over the network you can only get its name, its file structure and the structure of its subfolders. But you can't get any information about its parent folder and definitely not the whole directory structure of the hard disc on which the folder is physically located.

In fact the shared folder might not even be physically present on the computer from which it is shared. It can be a subfolder from some other shared network drive that some other computer shares.

Upvotes: 2

Related Questions