how to write on a partition that I previously lock (using Delphi)
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.
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.
精彩评论