Mega Code Archive

 
Categories / Delphi / Functions
 

Convert a Drive Letter (C) to a Drive Number (3) as Used by Delphis DiskFree function

Title: Convert a Drive Letter ("C") to a Drive Number (3) - as Used by Delphi's DiskFree function I have an application that needs to "export" a set of files into a specified folder on a drive. Files can come from various sources: hard disk, usb disk, network drive, etc. Before the export action an export folder needs to be specified, for example "c:\export folder". For a more user friendly approach, before the actual export I need to make sure there's enough space on the drive specified by the export folder. In the above case the drive I'm interested in is "C". If the export folder is set to "d:\some folder\export folder" then I need to find out how many bytes are available on the "D" drive. RTL's DiskFree function Lucky for us working in Delphi, we do not have to invent hot water. Most of the times Delphi already provides a function that serves the purpose, in the Run Time Library. DiskFree returns the amount of free space in bytes on a specified drive. There's a "but" :( DiskFree is declared as: function DiskFree(Drive: Byte): Int64; DiskFree function takes a byte (an integer type holding values from 0..255) value - while "C" in "c:\export folder" or "D" in "d:\some folder\export folder" is a character. The help for DiskFree states: DiskFree returns the number of free bytes on the specified drive, where 0 = Current, 1 = A, 2 = B, 3 = C, 4 = D and so on. The question is how to come from "D" to 4 (or from "E" to 5)? Here's the answer: var driveLetter : char; driveNumber : byte; directory : string; freeBytes : int64; begin //looking for free space on C drive directory := 'c:\Export Folder'; driveLetter := UpperCase(ExtractFileDrive(directory))[1]; driveNumber := 1 + Ord(driveLetter) - Ord('A') ; freeBytes := DiskFree(driveNumber) ; //here "freeBytes" holds the number of free bytes on a drive //specified by a directory end; Note: RTL's Ord returns an integer representing the ordinal value of an ordinal value. Character types are ordinal types (originally modeled after the ANSI character set) - this is why Ord('A') is 65 since 'A' holds a value of 65 in the ASCII table. Once you have the number of free bytes on a drive you can display it nicely to the user: Formatting a File Size in Bytes for Display.