how to write on a partition that I previously lock (using Delphi)

微笑、不失礼 提交于 2020-01-06 05:35:15

问题


I want to lock a partition, write a few files using TFileStream and then unlock it. I found how to lock and unlock but I don't know how to write. So far my code is:

Const
   FSCTL_LOCK_VOLUME = $00090018;
   FSCTL_UNLOCK_VOLUME = $0009001C;

var HLockedVol: THandle;

implementation

{$R *.dfm}

function LockDrive(Drive: AnsiChar): Boolean;
var
   OldMode: UINT;
   BytesReturned: Cardinal;
begin
   Result := False;

   OldMode := SetErrorMode(SEM_FAILCRITICALERRORS);
   try
      HLockedVol := CreateFile(PChar(Format('\\.\%s:', [AnsiLowerCase(string(Drive))])), GENERIC_READ, FILE_SHARE_READ or FILE_SHARE_WRITE, nil,
         OPEN_EXISTING, 0, 0);
      if HLockedVol <> INVALID_HANDLE_VALUE then
      begin
         Result := DeviceIoControl(HLockedVol, FSCTL_LOCK_VOLUME, nil, 0, nil, 0, BytesReturned, nil);
      end;
   finally
      SetErrorMode(OldMode);
   end;
end;

function UnlockDrive: Boolean;
var
   OldMode: UINT;
   BytesReturned: Cardinal;
begin
   Result := False;

   OldMode := SetErrorMode(SEM_FAILCRITICALERRORS);
   try
      if HLockedVol <> INVALID_HANDLE_VALUE then
      begin
         try
            Result := DeviceIoControl(HLockedVol, FSCTL_UNLOCK_VOLUME, nil, 0, nil, 0, BytesReturned, nil);
         finally
            CloseHandle(HLockedVol);
         end;
      end;
   finally
      SetErrorMode(OldMode);
   end;
end;

I'm suppose to use HLockedVol, but I don't know how...

Can you please help me? Thank you.


回答1:


You've opened something and received a file handle. To write to it, use WriteFile. You can wrap the handle inside a THandleStream if you're more comfortable with streams.

Note that when you do this, you are not writing files. You're writing directly to the disk, below the level of abstraction where such a concept as "file" exists. And you can't do I/O on any normal files in the meantime (because you locked the volume).

Although this is an answer to the question you asked, it's probably not a solution to your problem. I invite you to post a new question describing your problem; don't worry about the solution you're currently pursuing right now.



来源:https://stackoverflow.com/questions/4661504/how-to-write-on-a-partition-that-i-previously-lock-using-delphi

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!