Search code examples
delphicd

How to read a CD as a file?


I want to know whether it is possible in Delphi to read a CD as a raw Stream direct from the logical disk drive device "C:\".

I hope I could use a TFileStream if I have already a valid file handle.


Solution

  • It is easiest to use THandleStream rather than TFileStream in my view. Like this:

    procedure ReadFirstSector;
    var
      Handle: THandle;
      Stream: THandleStream;
      Buffer: array [1..512] of Byte;
      b: Byte;
    begin
      Handle := CreateFile('\\.\C:', GENERIC_READ,
        FILE_SHARE_READ or FILE_SHARE_WRITE, nil,
        OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
      if Handle=INVALID_HANDLE_VALUE then
        RaiseLastOSError;
      try
        Stream := THandleStream.Create(Handle);
        try
          Stream.ReadBuffer(Buffer, SizeOf(Buffer));
          for b in Buffer do
            Writeln(AnsiChar(b));
        finally
          Stream.Free;
        end;
      finally
        CloseHandle(Handle);
      end;
    end;
    

    Beware that when using raw disk access you have to read exactly multiples of sectors. The sectors on the disk I tested with are 512 bytes in size. I expect that CD disk sectors could very well be a different size.