Mega Code Archive

 
Categories / Delphi / Hardware
 

How to get a volume name of a drive

Title: How to get a volume name of a drive Question: How to get the name of a local or remote drive. Answer: For VolumeID the two important functions are SetErrorMode: for switch off the system error messages, GetVolumeInformation: for actually retrieving the name. For NetWorkVolume the important function is WNetGetConnection: for accessing a networkdrive. function VolumeID(DriveChar: Char): string; var OldErrorMode: Integer; NotUsed, VolFlags: Integer; Buf: array [0 .. MAX_PATH] of Char; begin OldErrorMode := SetErrorMode(SEM_FAILCRITICALERRORS); try if GetVolumeInformation(PChar(DriveChar + ':\'), Buf, sizeof(Buf), nil, NotUsed, VolFlags, nil, 0) then SetString(Result, Buf, StrLen(Buf)) else Result := ''; if DriveChar Result := AnsiUpperCaseFileName(Result) else Result := AnsiLowerCaseFileName(Result); Result := Format('%s',[Result]); finally SetErrorMode(OldErrorMode); end; end; function NetworkVolume(DriveChar: Char): string; var Buf: Array [0 .. MAX_PATH] of Char; DriveStr: array [0 .. 3] of Char; BufferSize: Integer; begin BufferSize := sizeof(Buf); DriveStr[0] := UpCase(DriveChar); DriveStr[1] := ':'; DriveStr[2] := #0; if WNetGetConnection(DriveStr, Buf, BufferSize) = WN_SUCCESS then begin SetString(Result, Buf, BufferSize); if DriveChar Result := AnsiUpperCaseFileName(Result) else Result := AnsiLowerCaseFileName(Result); end else Result := VolumeID(DriveChar); end;