使用delphi中的Tregistry类将reg_binary读取为字符串

use*_*977 1 delphi registry

我正在尝试从注册表项中获取 reg_binary 作为字符串。

这是我的功能

function ReadBinString(key: string; AttrName: string): string;
var
 ReadStr: TRegistry;

begin
// Result := '';
ReadStr := TRegistry.Create(KEY_WRITE OR KEY_WOW64_64KEY);
ReadStr.RootKey := HKEY_LOCAL_MACHINE;

   if ReadStr.OpenKey(key, true) then
begin

  Result := ReadStr.GetDataAsString(AttrName);
end;

ReadStr.CloseKey;
ReadStr.Free;
end;
Run Code Online (Sandbox Code Playgroud)

这是我的注册表项 Export :

 Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\ZES\ACINFO]
"iamthere"=dword:00000001
"ArrayOrder"=hex:4d,79,45,78,63,6c,75,64,65
Run Code Online (Sandbox Code Playgroud)

问题是,该函数返回空字符串

我什至尝试以管理员身份运行以确保它不是权限。

有什么帮助吗?

Dav*_*nan 5

扩展我对问题的评论,我将使用如下代码:

function ReadBinString(RootKey: HKEY; Access: LongWord; const KeyName,
  ValueName: string; Encoding: TEncoding): string;
var
  Registry: TRegistry;
  Bytes: TBytes;
begin
  Registry := TRegistry.Create(Access);
  try
    Registry.RootKey := RootKey;
    if Registry.OpenKeyReadOnly(KeyName) then begin
      SetLength(Bytes, Registry.GetDataSize(ValueName));
      Registry.ReadBinaryData(ValueName, Pointer(Bytes)^, Length(Bytes));
      Result := Encoding.GetString(Bytes);
    end else begin
      Result := '';
    end;
  finally
    Registry.Free;
  end;
end;
Run Code Online (Sandbox Code Playgroud)

对于您的数据,您可以这样称呼它:

Value := ReadBinString(HKEY_LOCAL_MACHINE, KEY_WOW64_64KEY, 'Software\ZES\ACINFO', 
  'ArrayOrder', TEncoding.ANSI);
Run Code Online (Sandbox Code Playgroud)

笔记:

  • 我避免了对根密钥进行硬编码。
  • 我曾经TEncoding将字节数组解码为文本。这远比 有效GetDataAsString
  • 我已允许调用者指定要使用的编码。
  • 我已允许调用者指定访问标志。
  • 我之所以使用,OpenKeyReadOnly是因为我们不需要写访问权限。