You were right, that was because of access privilege,
I wonder why saving a key to a file needs that privilege while reading, writing or even deleting a key within a program is done without that!!!
Anyhow I fixed the problem by below codes, I pose it in here in case if someone is interested in this topic.
I also mentioned a small useful function for moving a file to recycle bin , that is better than using DeleteFile function!
- Code: Select all
procedure SaveKeyTest;
Var
R: TRegistry;
begin
R:= TRegistry.Create;
Try
R.RootKey:= HKEY_CURRENT_USER;
If R.OpenKeyReadOnly('Softare\MyKey') Then
Begin
R.CloseKey;
EnableNTPrivilege('SeBackupPrivilege', SE_PRIVILEGE_ENABLED); //See below for this function
If FileExists('SavedKeyFile.reg') Then
SendToRecycleBin('SavedKeyFile.reg', False); //See Below or this function
// This saves the key in binaro format, To read the
// same key, set the privilege as above and use
//R.RestoreKey('Software\MyKey', 'SavedKeyFile.reg')
If R.SaveKey('Softare\MyKey', 'SavedKeyFile.reg') Then
Begin
//worked!!! Yippee!! woowoo!! Saved!
End
Else
Begin
//Sorry Failed!
End;
End;
Finally
R.Free;
End;
End;
// Setting Access Privilage
Function SetAccessPrivilege(Const PrivilegeStr : String; State : Integer):Integer;
Var
hToken : THandle;
aluid : TLargeInteger;
cbPrevTP : DWORD;
tp, fPrevTP : PTokenPrivileges;
Begin
result := 0;
If OpenProcessToken (GetCurrentProcess, TOKEN_ADJUST_PRIVILEGES Or
TOKEN_QUERY, hToken) Then
Try
LookupPrivilegeValue (Nil, PChar (PrivilegeStr), aluid);
cbPrevTP := SizeOf (TTokenPrivileges) + sizeof (TLUIDAndAttributes);
GetMem (tp, cbPrevTP);
GetMem (fPrevTP, cbPrevTP);
Try
tp^.PrivilegeCount := 1;
tp^.Privileges [0].Luid := aLuid;
tp^.Privileges [0].Attributes := State;
If Not AdjustTokenPrivileges (hToken, False, tp^, cbPrevTP, fPrevTP^, cbPrevTP) Then
RaiseLastWin32Error;
Result := fPrevTP^.Privileges [0].Attributes;
Finally
FreeMem (fPrevTP);
FreeMem (tp);
End
Finally
CloseHandle (hToken);
End
End;
// Sending a file to recucle bin
Function SendToRecycleBin(FileName: String; DoConfirm: Boolean): boolean;
Var
fos: TSHFileOpStruct;
i: Integer;
Begin
FillChar(fos, SizeOf(fos), 0);
With fos Do
Begin
wFunc:= FO_DELETE;
FileName:= FileName + #0 + #0;
pFrom:= @FileName[1];
fFlags:= FOF_ALLOWUNDO or FOF_SILENT;
If Not DoConfirm Then fFlags:= fFlags Or FOF_NOCONFIRMATION;
End;
i:= ShFileOperation(fos);
Result:= (i = 0);
End;