Einzelnen Beitrag anzeigen

Alter Mann

Registriert seit: 15. Nov 2003
Ort: Berlin
934 Beiträge
 
Delphi 10.2 Tokyo Professional
 
#1

WriteFile schreibt nichts!?

  Alt 27. Aug 2012, 14:02
Hallo,

wie sage ich es WriteFile?

Hintergrund, ich möchte ein paar Sektoren auf die HDD schreiben, also(schematisch):
Delphi-Quellcode:
...
  PInhaltsWert = ^TInhaltsWert;
  TInhaltsWert = packed record // Sizeof(TInhaltsWert) = 512;
  ...
  Size : WORD;
  ...
  end;
...
procedure SchreibeSektor(aDriveLetter : Char);
var
  dHandle : THandle;
  dLocked : Boolean;
  cBReturn : DWORD;
  IwRec : PInhaltsWert;
  I : Integer;
  Sector : DWORD;
begin
   dHandle := CreateFile(PChar(Format('\\.\%s:', [aDriveLetter])),
                        GENERIC_READ or GENERIC_WRITE,
                        FILE_SHARE_READ or FILE_SHARE_WRITE,
                        nil, OPEN_EXISTING, FILE_FLAG_NO_BUFFERING, 0);
   if dHandle <> INVALID_HANDLE_VALUE then
   begin
     dLocked := DeviceIoControl(dHandle, FSCTL_LOCK_VOLUME, nil, 0, nil, 0, cBReturn, nil);
     if dLocked then
     begin
      IwRec := VirtualAlloc(nil, 512, MEM_COMMIT or MEM_RESERVE, PAGE_READWRITE);
      if (IwRec <> nil) then
      begin
                  ...
        IwRec^.Size := SizeOf(TInhaltsWert);
                  ...
        Sector := 65;
        for I := 0 to 1 do
        begin
         if (I > 0) then Inc(Sector, 32 * 512);
         WriteSector(dHandle, IwRec, Sector, 512);
        end;
        VirtualFree(IwRec, 512, MEM_RELEASE);
      end;
      DeviceIoControl(dHandle, FSCTL_DISMOUNT_VOLUME, nil, 0, nil, 0, cBReturn, nil);
      DeviceIoControl(dHandle, FSCTL_UNLOCK_VOLUME, nil, 0, nil, 0, cBReturn, nil);
     end;
   end;
   CloseHandle(DriveHandle);
end;

function WriteSector(aHandle : THandle; const Data : Pointer; aPosition, aBytesPerSector : DWORD): Boolean;
var
  Position : DWORD;
  Offset : DWORD;
  BytesToWrite : DWORD;
begin
  Result := false;
  Position := aPosition * aBytesPerSector;
  Offset := (Position shr 32);

  if HandleValidated(aHandle) then
    if SetFilePointer(aHandle, Position, @Offset, FILE_BEGIN) = Position then
    begin
      if HandleValidated(aHandle) then
      begin
        Result := WriteFile(aHandle, Data, aBytesPerSector, BytesToWrite, nil);
        if ((BytesToWrite = 0) and (not Result)) then ShowSysError('WriteSector->WriteFile', GetLastError);
      end;
    end
    else ShowSysError('WriteSector->SetFilePointer', GetLastError);
end;
Egal was ich mache, das Ergebnis von WriteFile ist immer True, aber leider ist
auch BytesToWrite immer 0?

Auch ein Typloses const Data in WriteSector und ein Pointer(Data)^ in WriteFile
bringt mich nicht so richtig weiter.

Hat jemand einen Tipp?

Danke
  Mit Zitat antworten Zitat