3

I have a simple class derivated from THandleStream which I use to edit a raw volume. I call Windows createfile() function to open a drive but the function never returns a valid handle, rather an exotic error code( 348 at the debugtime and 304 at the runtime, but the error is not raised, this is just that the handle value looks wierd). this is what I'm doing:

Constructor TDiskStream.Create(Const aDrive: String);
Var
  Hdl: Cardinal;
  A,B: Int64;
Begin

  Hdl := CreateFile( PChar(ADrive), 
                     GENERIC_WRITE, 
                     FILE_SHARE_READ Or FILE_SHARE_WRITE, 
                     0, OPEN_EXISTING, 0, 0);

  Inherited Create( Hdl );
  GetDiskFreeSpaceEx( PChar( RightStr(ADrive,2) + '\'), A, FSize, @B );

End;

The handle value matchs to the error code described as ERROR_INCOMPATIBLE_WITH_GLOBAL_SHORT_NAME_REGISTRY_SETTING on msdn, but it seems to be very uncommon. The aDrive parameter is set correctly ( in the format \\.\x: ).

What's wrong here, how can I manage to get my valid file handle ?

az01
  • 39
  • 1
  • 2

2 Answers2

10

CreateFile does not return error codes - it returns either a valid handle or INVALID_HANDLE_VALUE (-1). Here is a standard use of CreateFile function call with error check:

var
  H: THandle;

begin
  H:= CreateFile(PChar('\\.\D:'), GENERIC_READ,
    FILE_SHARE_WRITE or FILE_SHARE_READ, nil,
    OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  if H = INVALID_HANDLE_VALUE then
    raise Exception.Create(Format('Oops - error opening disk: %d', [GetLastError]));
...
kludg
  • 27,213
  • 5
  • 67
  • 118
4

Those look like valid handle values to me. What makes you think they aren't?

CreateFile doesn't return error codes. If it fails, it returns Invalid_Handle_Value. The error code is given by calling GetLastError. For details on how those functions work, refer to the documentation on MSDN.

If CreateFile fails, I recommend you fail the constructor in turn by raising an exception:

if Hdl = Invalid_Handle_Value then
  RaiseLastOSError;
Rob Kennedy
  • 161,384
  • 21
  • 275
  • 467